I need to create a function in JavaScript that allows me to set values in nested objects using dynamic path strings or arrays. The path strings may include indices to specify the exact location where the value should be set. Additionally, the path strings can include "[]" notation to push values into arrays.
For instance, given an object like:
const obj = { foo: { bar: [] } };
I want to set a value at the path "foo.bar[][2]"
or "foo.bar[2][]".
The function should be able to handle both string and array representations of the path.
Here’s an example of what I’m looking for:
setValue(obj, 'foo.bar[][2]', 'value');
console.log(obj); // Output: { foo: { bar: [[ <2 empty items>, 'value' ] ] } }
setValue(obj, 'foo.bar[2][]', 'value');
console.log(obj); // Output: { foo: { bar: [ <2 empty items> , [ 'value' ] ] } }
How can I implement such a function efficiently in JavaScript?
2
Answers
You would have to create your own mixin to split the path, retrieve the existing value, and push a new value.
You will need a bit of RegExp-fu to check the incoming path.
We could take the lodash-style
set
function, but modify it to deal with[]
as a an indication to push a value to an array (if it is an array).Drawing on the
set
function provided in this answer, it could be this: