开发者

javascript - query object graph?

开发者 https://www.devze.com 2023-01-03 22:49 出处:网络
Given an object like this: var obj = { first:{ second:{ thir开发者_StackOverflowd:\'hi there\' } } }; And a key like this \"first.second.third\"

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消