Can anyone have a better solution to get and update nested object values with the dot notation string using javascript? I have an object say,
let user = { "fullname": { "firstname": "abc" "lastname": "xyz" } };
and I have a string with the dot notation which indicates what key needs to get or updated like “user.fullname.firstname” to “John Doe” for the updation. and the end output should be something like this,
{ "fullname": { "firstname": "John Doe" "lastname": "xyz" } }
You can use this approach via passing the data as an internal object, filed to be updated, and value of the field.
nestedObjectGetUpdate(data, field, value) { let schema = data; // a moving reference to internal objects within obj const pList = field.split('.'); const len = pList.length; for (var i = 0; i < len - 1; i++) { var elem = pList[i]; if (!schema[elem]) schema[elem] = {} schema = schema[elem]; } if (!value) { return schema[pList[len - 1]]; } schema[pList[len - 1]] = value; }
Awesome. Working as expected.