如何使用一组键来从Javascript对象中获取值

时间:2017-10-28 20:19:40

标签: javascript

如果有一个具有多个级别的Javascript对象,如:

myObject = {
        a: 12,
        obj11: {
                obj111: 'John',
                b:13,
                obj1111: { a:15, b: 35 } 
        },
        obj21: { 
                a:15,
                b:16 }
        }

我想编写一个传递对象和键数组的函数。该函数应该根据这些键返回一个值。例如,传递[obj11,b]应该返回13.传递[obj11,obj1111,a]应该返回15.传递obj21应该返回对象{a:15,b:16}

  function (myObj,myArr) {

      return keyVal;
  }

假设密钥总是正确的,有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

您可以使用reduce()一行进行此操作。当然,如果你想将它包装在一个函数中,你也可以这样做。



var myObject = {
    a: 12,
   obj11: {
           obj111: 'John',
           b:13,
           obj1111: { a:15,
                      b: 35 }
           },
   obj21: {
           a:15,
           b:16 }
}

var arr =   ['obj11','b']
var val = arr.reduce((acc,curr) => acc[curr], myObject)
console.log(val)

var arr =   ['obj11','obj1111', 'b']
var val = arr.reduce((acc,curr) => acc[curr], myObject)
console.log(val)




答案 1 :(得分:3)

您可以使用键缩小数组并将对象作为默认值。

function getValue(object, path) {
    return path.reduce(function (r, k) {
        return (r || {})[k];
    }, object);
}

var object = { a: 12, obj11: { obj111: 'John', b: 13, obj1111: { a: 15, b: 35 }, obj21: { a: 15, b: 16 } } };

console.log(getValue(object, ['obj11', 'b']));
console.log(getValue(object, ['obj11', 'obj1111', 'a']));
console.log(getValue(object, ['obj11', 'obj21']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

要增加讨论,如果您使用lodash,您还可以使用函数_.get来获取如下值:

_.get(myObject, ['obj111', 'obj1111'])
//returns 'John'

如果您的对象具有包含数组值的属性,您也可以通过索引获取

var obj = {
        a: 1,
        b:[{
           d:4,
           c:8
        }]

_.get(obj, ['b','0','d'])
//returns 4

来源:https://lodash.com/docs/4.17.4#get