Access to object property with dynamic name and dy

2019-07-28 00:12发布

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.

2条回答
来,给爷笑一个
2楼-- · 2019-07-28 00:27

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

查看更多
冷血范
3楼-- · 2019-07-28 00:38

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

查看更多
登录 后发表回答