Getting an Objects nested value from an array of nested properties

后端 未结 1 1870
心在旅途
心在旅途 2021-01-28 02:36

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.



        
相关标签:
1条回答
  • 2021-01-28 03:36

    Perhaps something like this?

    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
    

    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;    
    }
    
    0 讨论(0)
提交回复
热议问题