If we have a nested object and wanted to use a variable to access the value of one of its keys, we can use eval
like this:
var oldObj = {
part1: {
part2: {
part3: 'abc',
}
}
};
var string = 'part1.part2.part3';
var value = eval('oldObj.' + string);
console.log(value);
How can I still use a variable to access the object value, change it, then return the entire new object?
Something like:
function changeVal(obj, keysAsString, newValue) {
/* What do I need to do here??? */
}
var newObj = changeVal(oldObj, string, 'xyz');
console.log(newObj);
How can I get a final output like this:
{
part1: {
part2: {
part3: 'xyz'
}
}
}