关闭我的previous question(关于获取属性),我需要使用动态属性名称设置嵌套对象成员的值。
const settings = {
service: {
username: 'foo',
password: 'bar'
}
};
const settingName = 'service.username';
const newValue = 'baz';
settings[settingName] = newValue ; // doesn't work
console.log(settings.service.username); // foo
我能想到的唯一方法是使用eval:
eval(`settings.${settingName} = "${newValue}"`);
const settings = {
service: {
username: 'foo',
password: 'bar'
}
}
const settingName = 'service.username';
const newValue = 'baz';
eval(`settings.${settingName} = "${newValue}"`); // works, but bad
console.log(settings.service.username);
但这有问题(例如,上面的例子假设新值是一个字符串)。 有没有办法在不使用eval的情况下分配名称未知的嵌套对象的属性?
答案 0 :(得分:1)
你可以像下面这样做,
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
function setValue(obj, keys, val){
keys.split(".").forEach(function(itm, i, arr){
if (i == arr.length - 1) obj[itm] = val;
else obj = obj[itm];
});
}
setValue(settings, key, "hello");
console.log(settings.service.username); //"hello"
答案 1 :(得分:0)
也是对我之前回答的跟进:是。
我们可以使用Function
构造函数来创建和运行将按名称设置属性的代码,就像使用常规的点属性访问一样。
const settings = {
service: {
username: 'foo',
password: 'bar'
}
};
const settingName = 'service.username';
const newValue = 'baz';
Function('settings', 'value', 'settings.' + settingName + ' = value')(settings, newValue);
console.log(settings.service.username); // "baz"