且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 08:00:57

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



var obj = {type:Purchase,category:Apartment,categoryOptions:{apartment :{floor:{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)


How can I get a value from a nested object, using an array of keys?

// 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"]

I tried to use array.reduceRight to achieve this but could not make it work.

here is what I've tried :

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'

is there any way so I can get the proper key to pass to obj here?

You definitely can use reduceRight for this. The problem is that you created a string, however you need to pass your object as initialValue and use the squared bracket notation:

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)