Skip to content Skip to sidebar Skip to footer

Access Nested Property By Path

I'm trying to access to nested properties of an object from a string. Here is my sample code : var obj = { 'text': 'hello', 'foo': { 'float': 0.5, 'bar': { 'id':

Solution 1:

You'll have to do a little bit of traversal for that.

Split the path by it's ., then Array.reduce over the parts with each iteration accessing the property it refers to via a bracket-notation accessor.

Eventually you'll reach the value you're after.

var obj = {
  'text': 'hello',
  'foo': {
    'float': 0.5,
    'bar': {
      'id': 42,
      'baz': [{ name: 'Mary' }, { name: 'Jane' }]
    }
  }
};

vargetValueByPath = (obj, path) =>
  path.split('.').reduce((acc, part) => acc ? acc[part] : undefined, obj);

var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';
var keyFour = 'foo.bar.baz.1.name';

console.log(getValueByPath(obj, keyOne));
console.log(getValueByPath(obj, keyTwo));
console.log(getValueByPath(obj, keyThree));
console.log(getValueByPath(obj, keyFour));

Solution 2:

Whats wrong with accessing like this? is there a reason you need the keys to be defined in variables?

Hope this helps :)

var obj = {
  text: 'hello',
  foo: {
    float: 0.5,
    bar: {
      id: 42,
    },
  },
};

console.log(obj.text);
console.log(obj.foo.float);
console.log(obj.foo.bar.id);

Post a Comment for "Access Nested Property By Path"