Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lodash to deep set without creating undefined values

Given this example using lodash:

var object = {};
_.set(object, [ 1, 2 ], 5);
console.log(object);

The resultant object in the console is:

{
  1: [undefined, undefined, 5]
}

Now imagine, instead of the integer 2, you are setting a timestamp of 1445231475. You now have 1445231474 undefined values in a very large array that will run out of memory after a few _.set operations.

If possible with _.set, how would one go about creating this object:

{
  1: {
    2: 5
  }
}

It is possible if 2 is truly a string like "a", but Lodash will force even "2" into the array of multiple undefined values.

I can use _.merge if necessary, but I would be more excited about using _.set capability.

like image 963
ryanm Avatar asked Oct 19 '15 06:10

ryanm


1 Answers

you can do this with lodash setWith

// unwanted behavior with set
let x = {}
_.set(x, [1,2], 'test')
// x = { '1': [ <2 empty items>, 'test' ] }

// desired behavior with setWith
let y = {}
_.setWith(y, [1,2], 'test', Object)
// y = { '1': { '2': 'test' } }
like image 182
FFF Avatar answered Sep 19 '22 17:09

FFF