如何使用键数组从Javascript对象获取值
问题描述:
如果存在一个具有多个级别的Javascript对象,例如:
If there is a Javascript object with multiple levels, as in:
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}
I want to write a function to which is passed the object and an array of keys. The function should return a value based upon these keys. For example, passing [obj11,b] should return 13. Passing [obj11, obj1111,a] should return 15. Passing obj21 should return the object {a:15, b:16}
function (myObj,myArr) {
return keyVal;
}
假设键总是正确的,谁能帮助我解决这个问题?
Assuming that the keys are always correct, can anyone help me solve this problem?
答
您可以使用键来缩小数组并将对象作为默认值.
You could reduce the array with the keys and take an object as default value.
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; }