在我的项目中,我面临以下问题。我有一个非常复杂的结果对象,与此类似:
results = {
a : { b : { c : value1 }},
d : value2,
e : { f : value3 }
}
我想获得一种动态方式来获取基于字符串的特定值,例如:
//example 1
const string = '.a.b.c';
const value = results['a']['b']['c']; // = value1
// example 2
const string2 = '.e.f';
const value2 = results['e']['f']; // = value3
我从来不知道我需要的值(value)有多“深”。 (直接键、子键、子子键...)
我首先分割字符串并获取数组中的键:
const keys = string.split('.') // = ['a','b','c']
但是我不知道如何动态地获取我需要的值。我可以为具有 1、2、3 或 4 个(或更多)键的情况做出 if 语句,但我确信可能有一种动态、更干净的方法来管理它。有人有什么想法吗?
有关信息,if 语句是
if (keys.length === 1) {
value = results[keys[0]];
} else if (keys.length === 2) {
value = results[keys[0]][keys[1]];
} // and so on...
最佳答案
您可以使用split
和reduce
来实现这一点
let results = {
a : { b : { c : 'value1' }},
d : 'value2',
e : { f : 'value3' }
}
function getValue(str) {
return str.split('.').reduce((o, d) => o[d], results)
}
console.log(getValue('a.b.c'))
console.log(getValue('e.f'))
关于Javascript - 根据键字符串从对象动态获取子值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432122/