2

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': 42
    }
  }
};

var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';

console.log(obj[keyOne]); // successfully log 'hello'
console.log(obj[keyTwo]); // trying to log '0.5'
console.log(obj[keyThree]); // trying to log '42'

I'm trying to do it in JS but I also have jQuery ready for a cleaner solution.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Possible duplicate of [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Ulysse BN Sep 16 '19 at 22:56

2 Answers2

4

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' }]
    }
  }
};

var getValueByPath = (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));
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
0

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);
sjdm
  • 591
  • 4
  • 10