Skip to content Skip to sidebar Skip to footer

Access To Object Property With Dynamic Name And Dynamic Nesting Level

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 separ

Solution 1:

You could split the path and use the parts as properties for the given object.

functiongetValue(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); // Brendaconsole.log(getValue(o, 'Z.Y.X'));       // undefined

For better use with dots in properties, you could use an array directly to avoid wrong splitting.

functiongetValue(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'])); // Brendaconsole.log(getValue(o, ['Z.Y.X']));             // undefined

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

Post a Comment for "Access To Object Property With Dynamic Name And Dynamic Nesting Level"