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 travers
Solution 1:
Perhaps something like this?
functiongetValueAt(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
However it's not efficient for non-existing properties, since it will not short-circuit.
Here's another approach without using reduce
:
functiongetValueAt(o, keyPathArray) {
var i = 0,
len = keyPathArray.length;
while (o != null && i < len) o = o[keyPathArray[i++]];
return o;
}
Post a Comment for "Getting An Objects Nested Value From An Array Of Nested Properties"