上下文:我正在为我的应用程序设置编写一个 Redux 减速器(尽管这个问题不是特定于 Redux 的),它是一个嵌套对象。我想使用动态给出的属性名称来修改设置对象。
Example:
const settings = {
service: {
username: 'TEST',
password: ''
}
}
// Normally this would be passed by Redux, but for the purposes of this exercise it's hardcoded
const settingKey = 'service.username';
console.log(settings[settingKey]); // undefined
console.log(eval(`settings.${settingKey}`)); // works, but bad
我能想到的在不使用 eval 的情况下访问子对象的唯一方法是使用正则表达式来分割settingKey
进入其组成部分:
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
const settings = {
service: {
username: 'TEST',
password: ''
}
}
const settingKey = 'service.username';
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]]);
这可行,但是
- 它很丑
- 它不适用于更深层嵌套的对象
有没有一种方法可以在不使用正则表达式或 eval 的情况下使用动态名称访问嵌套对象的属性?
你可以做这样的事情,
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
function getValue(obj, keys){
keys.split(".").forEach(function(itm){
obj = obj[itm];
});
return obj;
}
getValue(settings, key); //"TEST"
或者你可以简单地使用Array#reduce
,
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username", result = key.split(".").reduce((a,b) => a[b], settings);
console.log(result); // "TEST"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)