从嵌套属性数组中获取对象的嵌套值 [英] Getting an Objects nested value from an array of nested properties
问题描述
我遇到一种情况,需要将两个对象压缩在一起,同时保留两个值.我可以遍历两个对象并构建所有键的数组.
I have a situation where I need to zip two Objects together retaining both of the values. I can iterate through both the objects and build an array of all the keys.
var traverse = function (obj, chain) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var tempChain = [].concat(chain || []);
tempChain.push(prop);
if (typeof obj[prop] === 'object') {
traverse(obj[prop], tempChain);
}
console.log(tempChain);
}
}
};
传递以下内容:
traverse({
'a': {
'b': 'hello world',
'b1': 'hello world 1',
'c': {
'd': 'dello'
}
}
})
将退还给我:
[a]
[a,b]
[a,b1]
[a,c]
[a, c, d]
所以我现在在对象中有一个嵌套属性数组.我如何才能访问obj [[a,c,d]]?我知道我可以通过评估解决问题,但是我不相信内容.
So I now have an array of nested properties in an object. How can I access essentially obj[[a,c,d]]? I know I can solve the problem through eval but I can't trust the content.
eval('window.' + ['a','c','d'].join('.'));
如果我可以遍历该数组并检查两个属性中是否都存在该属性,则构建一个合并了压缩"值的新对象.
If I can loop through that array and check to see if the property exists in both of them, then build a new object of the combined 'zipped' values.
推荐答案
也许是这样的事情?
function getValueAt(obj, keyPathArray) {
var emptyObj = {};
return keyPathArray.reduce(function (o, key) {
return (o || emptyObj)[key];
}, obj);
}
然后您可以像使用它一样
Then you can use it like:
var o = { a: { c: { d: 1 } } };
getValueAt(o, ['a', 'c', 'd']); //1
但是,对于不存在的属性来说效率不高,因为它不会短路.
这是不使用reduce
的另一种方法:
However it's not efficient for non-existing properties, since it will not short-circuit.
Here's another approach without using reduce
:
function getValueAt(o, keyPathArray) {
var i = 0,
len = keyPathArray.length;
while (o != null && i < len) o = o[keyPathArray[i++]];
return o;
}
这篇关于从嵌套属性数组中获取对象的嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!