Access to object property with dynamic name and dynamic nesting level

扶醉桌前 提交于 2019-12-11 04:59:13

问题


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])

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])

in consequence of the string: level1.level2.property.

Thank you in advance.


回答1:


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



回答2:


This should do it :

const str = 'level1.level2.property';
let value = { //workerFunctions;
  level1: {
    level2: {
      property: 'this is the value'
    }
  }
};
str.split(/\./).forEach((prop) => {
  value = value[prop];
});
console.log(value);


来源:https://stackoverflow.com/questions/42598589/access-to-object-property-with-dynamic-name-and-dynamic-nesting-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!