【问题标题】:javascript - query object graph?javascript - 查询对象图?
【发布时间】:2010-06-16 23:38:09
【问题描述】:

给定一个像这样的对象:

var obj = {
        first:{
            second:{
                third:'hi there'
            }
        }
    };

还有一个像“first.second.third”这样的键

如何获取嵌套对象“hi there”的值?

我认为 Array.reduce 函数可能会有所帮助,但不确定。

【问题讨论】:

    标签: javascript object


    【解决方案1】:

    是的,使用Array.prototype.reduce,您可以获得一个甜蜜而简短的功能:

    function getNestedValue(obj, key) {
      return key.split('.').reduce(function (a, b) { return a[b]; }, obj);
    }
    
    getNestedValue(obj, "first.second.third"); // "hi there"
    

    一些注意事项:

    • Array.prototype.reduce 是 ECMAScript 第 5 版的一部分,可在除 IE 之外的所有浏览器上使用,您可以包含来自 here 的实现。
    • 如果您使用方括号表示法构建对象,则对象属性名称可能包含点,例如obj['my.key'] = 'value';

    【讨论】:

      【解决方案2】:

      知道了:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-26
        • 2016-12-04
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-05
        相关资源
        最近更新 更多