Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a nested property with a string [duplicate]

Tags:

javascript

var person = {
  name: 'Joe',
  contact: {
    phone: '555'
  }
}

var nameOfPerson = person['name']; //Joe

var str = 'contact.phone';
var phoneToPerson = person[str]; //undefined

Is this possible to do somehow? I got some logic where I end up with a string and I need to access a nested property with it.

https://jsbin.com/xehokozaco/edit?js,console

like image 709
Joe Avatar asked Oct 11 '15 15:10

Joe


2 Answers

You'll have to split the string by the period, and then access each node iteratively. This could be done in a simple reduce:

var value = str.split('.').reduce(function(p,prop) { return p[prop] }, person);

The above would work regardless if str contains a period or not, i.e. for name as well as contact.phone.

like image 195
David Hedlund Avatar answered Sep 30 '22 14:09

David Hedlund


You can by splitting the string. the [..] operator lets you access object properties by name (and array items index). In a case of nested objects, you simply access them one after the other.

Try like this:

var person = {
  name: 'Joe',
  contact: {
    phone: '555'
  }
}

var nameOfPerson = person['name']; //Joe

var str = 'contact.phone';

var phoneToPerson = str.split('.').reduce(function(o, key) {
  return o[key];
}, person);

alert(phoneToPerson);
like image 26
Amit Avatar answered Sep 30 '22 15:09

Amit