JavaScript - 使用键数组从嵌套对象中检索值

时间:2017-06-16 13:39:58

标签: javascript arrays javascript-objects

如何使用键数组从嵌套对象中获取值?

// my sample object
var obj = {
    type            : "Purchase",
    category        : "Apartment",
    categoryOptions : {
       apartment : {
           floors    : {
               type        : "number",
               value       : null,
               placeholder : "Total Floors"
           },
       },
    },
}
var keysArray = ["value", "floors", "apartment", "categoryOptions"]

我尝试使用array.reduceRight来实现此功能,但无法使其正常运行。

这是我尝试过的:

var roadToValue = keysArray.reduceRight(
    function(previousValue, currentValue){
        return previousValue + "[" + currentValue + "]" ;
    }
);
// above function results in a single string like 
// "categoryOptions[apartment][floors][value]" 
// which off-course can't be used as object key
// and obj[roadToValue] results in 'undefined'

有什么办法让我可以在这里找到传递给obj的正确密钥吗?

1 个答案:

答案 0 :(得分:5)

你绝对可以使用reduceRight。问题是您创建了一个字符串,但是您需要将对象作为initialValue传递并使用方括号括号:

var obj = {"type":"Purchase","category":"Apartment","categoryOptions":{"apartment":{"floors":{"type":"number","value":null,"placeholder":"Total Floors"}}}}
var keysArray = ["value", "floors", "apartment", "categoryOptions"]

var value = keysArray.reduceRight((r, e) => r[e] || r, obj)
console.log(value)