If I have an object like this...
var rooter = {
name: 'Billy',
lastName: 'Moon',
height: '1.4m'
}
I can access the properties from variables like this...
var name = "name"
console.log(rooter[name])
var arb = "height"
console.log(rooter[arb])
Happy days!
However, if I have a more deeply nested object, and I want to get a leaf described by an address in a string...
var rooter = {
user: {
firstName: 'Billy',
lastName: 'Moon',
arbitrary: {
namespace: {
height: '1.4m'
}
}
}
}
var name = "user.lastName"
console.log(rooter[name]) // does not work
var arb = "user.arbitrary.namespace.height"
console.log(rooter[arb]) // does not work
No dice :(
How can I access arbitrary object leaves from a string describing the path?
EDIT: Found method with underscore...
_.reduce(arb.split('.'), function(m, n){ return m[n] }, rooter)
and for IE 9 and above...
arb.split('.').reduce(function(m, n){ return m[n] }, rooter)