Getting nested obj value

前端 未结 2 461
滥情空心
滥情空心 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(".")));
    

提交回复
热议问题