Skip to content Skip to sidebar Skip to footer

Access A Nested Property With A String

var person = { name: 'Joe', contact: { phone: '555' } } var nameOfPerson = person['name']; //Joe var str = 'contact.phone'; var phoneToPerson = person[str]; //undefined

Solution 1:

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.

Solution 2:

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']; //Joevar str = 'contact.phone';

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

alert(phoneToPerson);

Solution 3:

try

var select = "contact.phone";
var value = person;
select.split(".").forEach(function(val){
  value = value[val];
});
console.log(value);

Solution 4:

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.

Solution 5:

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:

varobject = { 
     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

Post a Comment for "Access A Nested Property With A String"