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
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With