Getting nested obj value

前端 未结 2 460
滥情空心
滥情空心 2021-01-21 11:41

Given the following obj:

var inputMapping = {
 nonNestedItem: \"someItem here\",
 sections: {
   general: \"Some general section information\" 
 }
};


        
相关标签:
2条回答
  • 2021-01-21 11:43

    You can use Array.prototype.reduce function like this

    var accessString = "sections.general";
    
    console.log(accessString.split(".").reduce(function(previous, current) {
        return previous[current];
    }, inputMapping));
    

    Output

    Some general section information
    

    If your environment doesn't support reduce, you can use this recursive version

    function getNestedItem(currentObject, listOfKeys) {
        if (listOfKeys.length === 0 || !currentObject) {
            return currentObject;
        }
        return getNestedItem(currentObject[listOfKeys[0]], listOfKeys.slice(1));
    }
    console.log(getNestedItem(inputMapping, "sections.general".split(".")));
    
    0 讨论(0)
  • 2021-01-21 11:49

    You don't need to use eval() here. You can just use [] to get values from an object. Use a temp object to hold the current value, then update it each time you need the next key.

    function getNode(mapping, name) {
        var n = name.split(".");
    
        if (n.length === 1) {
            return mapping[name];
        } else {
            var tmp = mapping;
            for (var i = 0; i < n.length; i++) {
                tmp = tmp[n[i]];
            }
            return tmp;
        }
    }
    
    0 讨论(0)
提交回复
热议问题