Access a nested property with a string [duplicate]
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']; //Joe
var 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);