JavaScript - 使用键数组从嵌套对象中检索值 [英] JavaScript - retrieve value from nested object, using array of keys

查看:77
本文介绍了JavaScript - 使用键数组从嵌套对象中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  //我的示例对象
var obj = {
类型:购买,
类别:公寓,
类别选项:{
公寓:{
楼层:{
类型:数字,
值:null,
占位符:总楼层
},
},
},
}
var keysArray = [value,floors,apartment,categoryOptions]

我尝试使用 array.reduceRight 实现这一目标但无法使其发挥作用。



这是我试过的:

  var roadToValue = keysArray.reduceRight(
function(previousValue,currentValue){
return previousValue +[+ currentValue +];
}
);
//上面的函数会产生一个单独的字符串,比如
//categoryOptions [apartment] [floors] [value]
//哪个off-course不能用作对象键
//和obj [roadToValue]导致'undefined'

有没有办法如此我可以在这里获得传递给obj的正确密钥吗?

解决方案

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



< pre class =snippet-code-js lang-js prettyprint-override> 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)

这篇关于JavaScript - 使用键数组从嵌套对象中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆