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
You need to split the path and use it as keys for the object.
If the key is not an object, a new object is created.
function set(obj, path, value) { var p = path.split('.'), last = p.pop(); p.reduce(function (o, k) { if (typeof o[k] !== 'object') { o[k] = {}; } return o[k]; }, obj)[last] = value; } var obj = { a: { value: 1 } }; set(obj, 'a.value', 'work'); set(obj, 'b.value', 42); set(obj, 'c', 'c'); console.log(obj); set(obj, 'c.value', 'work'); console.log(obj);
ES6
function set(obj, path, value) { var p = path.split('.'), last = p.pop(); p.reduce((o, k) => o[k] = typeof o[k] === 'object' ? o[k] : {}, obj)[last] = value; } var obj = { a: { value: 1 } }; set(obj, 'a.value', 'work'); set(obj, 'b.value', 42); set(obj, 'c', 'c'); console.log(obj); set(obj, 'c.value', 'work'); console.log(obj);
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));
您可以尝试使用eval()
eval('obj.'+str + '="work"');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.