Yauheni Kastsiukevich Yauheni Kastsiukevich - 5 months ago 21
JSON Question

[JS]Change multi level object value

var obj = {
a:{
value: 1
}
}

var str = 'a.value';

obj[str] = 'work';
console.log(obj);


I have this code, I need to change the value of the object using the string

Answer

Solution with recursion

var obj = {
    a: {
        value: 1
    }
}

var str = 'a.value';

var a = str.split('.');

(function f(o, v, i) {
    if (i == a.length - 1) {
        o[a[i]] = v; return;
    }
    f(o[a[i]], v, ++i);
})(obj, 'work', 0);

document.write('<pre>' + JSON.stringify(obj, 0, 2) + '</pre>');