使用动态名称和动态嵌套级别访问对象属性 [英] Access to object property with dynamic name and dynamic nesting level
问题描述
我从一个字符串读取了要访问的对象的属性:level1.level2.property或level1.property OR ...名称和嵌套可能有所不同.我将对象存储在单独的模块(workerFunctions)中.
I read the property of an object I want to access from a string: level1.level2.property OR level1.property OR ... The names and the nesting may vary. I store the objects in a separate module (workerFunctions).
我知道我可以使用[]表示法动态访问对象,例如:
I know that I can access the objects dynamically with the []notation, e.g.:
var level1="level1";
var property="property";
console.log(workerFunctions[level1][property])
但是,我不知道如何从变化的输入字符串中动态构造此"workerFunctions [level1] [property]",从而产生例如:
However, I don't know how to construct this "workerFunctions[level1][property]" dynamically from varying input strings, so to produce e.g.:
console.log(workerFunctions[level1][level2][property])
由于字符串:level1.level2.property.
in consequence of the string: level1.level2.property.
谢谢.
推荐答案
您可以拆分路径并将零件用作给定对象的属性.
You could split the path and use the parts as properties for the given object.
function getValue(o, path) {
return path.split('.').reduce(function (o, k) {
return (o || {})[k];
}, o);
}
var o = { A : { B: { C: { value: 'Brenda' } } } };
console.log(getValue(o, 'A.B.C').value); // Brenda
console.log(getValue(o, 'Z.Y.X')); // undefined
为了更好地使用属性中的点,可以直接使用数组以避免错误分割.
For better use with dots in properties, you could use an array directly to avoid wrong splitting.
function getValue(o, path) {
return path.reduce(function (o, k) {
return (o || {})[k];
}, o);
}
var o = { A : { 'B.C': { value: 'Brenda' } } };
console.log(getValue(o, ['A', 'B.C', 'value'])); // Brenda
console.log(getValue(o, ['Z.Y.X'])); // undefined
这篇关于使用动态名称和动态嵌套级别访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!