Guillaume S
Guillaume S

Reputation: 88

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': 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.

Upvotes: 2

Views: 128

Answers (2)

nicholaswmin
nicholaswmin

Reputation: 22989

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

Upvotes: 4

sjdm
sjdm

Reputation: 589

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

Upvotes: 0

Related Questions