编程语言
首页 > 编程语言> > JavaScript – 使用键数组从嵌套对象中检索值

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

作者:互联网

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

// 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吗?

解决方法:

你绝对可以使用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)

标签:javascript,arrays,javascript-objects
来源: https://codeday.me/bug/20191002/1844870.html