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
Solution with recursion
var obj = {
a: {
value: 1
}
}
var str = 'a.value';
function change(obj, prop, newValue) {
var a = prop.split('.');
return (function f(o, v, i) {
if (i == a.length - 1) {
o[a[i]] = v;
return o;
}
return f(o[a[i]], v, ++i);
})(obj, newValue, 0);
}
var result = change(obj, str, 'work');
console.log(JSON.stringify(obj, 0, 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With