I have a storage object that has an object datastore in it, like so:
data = {
name1: 'value1',
name2: 'value2',
child: {
name3: 'value3',
name4: 'value4'
}
}
What I need to do is pass the data variable, a name, and value, and have the object update, like so:
update(data, 'name1', 'foobar');
This works fine, but here's the catch: I need to be able to send a dot-notation name and have it update the proper child attribute. For instance:
update(data, 'child.name3', 'foobar');
Here is the code I'm using to do the traversal:
function update(data, fieldName, value) {
var field = data
var fieldNameParts = fieldName.split('.');
while (fieldNameParts.length)
field = field[fieldNameParts.shift()];
field = (value === undefined) ? null : value;
}
So the problem is that "field" contains the new value, but "data.child.name3" does not. How do I traverse and update the main data object?
Any ideas on how to solve this?
lodash.set?