Given an object like this:
var obj = {
first:{
second:{
thir开发者_StackOverflowd:'hi there'
}
}
};
And a key like this "first.second.third"
How can I get the value of the nested object "hi there"?
I think maybe the Array.reduce function could help, but not sure.
Yes, with Array.prototype.reduce
you can get a sweet and short function:
function getNestedValue(obj, key) {
return key.split('.').reduce(function (a, b) { return a[b]; }, obj);
}
getNestedValue(obj, "first.second.third"); // "hi there"
Some notes:
Array.prototype.reduce
is part of the ECMAScript 5th Edition, is available on all browsers except IE, you can include an implementation from here.- Object property names might contain dots, if you build an object using the bracket notation e.g.
obj['my.key'] = 'value';
Got it:
args.reduce(function(prev, current) {return prev[current];}, obj);
精彩评论