0

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'
        }
    }
}
user7607751
  • 465
  • 7
  • 27
  • 1
    If you want to keep using `eval`, just `eval('oldObj.' + string + ' = value;');` assuming `value` is a variable containing the value you want to set (or of course, just put the actual value there, e.g. `= "42";`). But look at the linked question's answers for better ways to go about this... – T.J. Crowder Sep 10 '19 at 16:50
  • Thank you @T.J.Crowder. My search before asking led to the question you linked, but, unfortunately, I couldn't figure it out still. What I want to do is **merging** the new value with the old object and return **the entire new object**, not just the new value. – user7607751 Sep 10 '19 at 17:08
  • The appropriate duplicate might be [Dynamically set property of nested object](https://stackoverflow.com/q/18936915/215552) in that case. – Heretic Monkey Sep 10 '19 at 17:20

0 Answers0