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.
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' } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With