7
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

Joe
  • 4,274
  • 32
  • 95
  • 175

5 Answers5

18

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.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
4

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);
Amit
  • 45,440
  • 9
  • 78
  • 110
1

try

var select = "contact.phone";
var value = person;
select.split(".").forEach(function(val){
  value = value[val];
});
console.log(value);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Natively, no. However there are way to do it, like splitting the string by . and recursively descend from the person object. It's also possible by evaluating the full string in eval or new Function, but I highly discourage for security reasons.

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

I know this post is quite old but its strange I can't see very popular "Lodash" solution here which allows to get object nested properties safely.

Example:

var object = { 
     a: [
       { 
         b: { 
           c: 3 
         } 
       }
     ]
 };

_.get(object, 'a[0].b.c'); // → 3

For your example:

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

var personPhoneProp = 'contact.phone';

_.get(person, personPhoneProp); // -> '555'

Documentation: https://lodash.com/docs#get

Evgeny Sorokin
  • 630
  • 3
  • 12