Kalle Aaltonen Kalle Aaltonen - 2 months ago 17
Javascript Question

lodash paths with numbers

_.set()
seems to be behaving strangely with paths that contain numbers

> _.set({}, [2], 1)
{ '2': 1 }


This seems reasonable. However:

> _.set({}, [2,2], 1)
{ '2': [ , , 1 ] }


I understand that the second path part is considered to be an array index. If I use strings:

> _.set({}, ["2","2"], 1)
{ '2': [ , , 1 ] }


I was expecting

{ '2': { '2' : 1} }


Is there anyway around this behaviour, other than checking that your path doesn't contain numerish field names?

EDIT: Solution:

_.setWith({}, [2, 2], 1, Object)
{ '2': { '2': 1 } }

Answer

The second argument is not an array index. It is an object path. Object path cannot be an array with two values.

For example on using it correct:

_.set(object, 'a[0].b.c', 4);

If your expected result was an object with a sub-path, you can use this:

_.setWith(object, '[0][1]', 'a', Object);

// => { '0': { '1': 'a' } } 
Comments