r = {
foo: {
bar: 'value'
},
foo2: 'value2'
}
var
path = 'aaa.bbb.ccc.ddd',
data = {
aaa: {
bbb: {
ccc: {
ddd: 'Hello!!'
}
}
}
};
console.log(path.split('.').reduce((p, c) => p[c], data)); // Hello!!
function bad( obj, name) {
return eval('obj.' + name);
}
bad(r, 'foo.bar'); // 'value'
function better( obj, name) {
var parts = name.split('.'), i, cursor = r;
for( i = 0; i < parts.length; i++) {
if( !cursor.hasOwnProperty( parts[i])) throw('No such property: ' + parts[i]);
cursor = cursor[parts[i]];
}
return cursor;
}
better(r, 'foo.bar'); // 'value'
var data = {
a: {
b: {
c: {
d: {
e: "Hello World!"
}
}
}
}
}
function from(target, path) {
return path.split(".").reduce(function(data, key) {
return data && data[key]
}, target)
}
console.log(from(data, "a.b.c.d.e")) // "Hello World!"
console.log(from(data, "a.a.a.a.a")) // undefined