views:

28

answers:

2

Given an object like this:

var obj = {
        first:{
            second:{
                third:'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.

+3  A: 

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';
CMS
yup, just figured it out as you posted. thanks.
Scott
+2  A: 

Got it:

args.reduce(function(prev, current) {return prev[current];}, obj);
Scott