JavaScript - retrieve value from nested object, using array of keys

前端 未结 1 964
故里飘歌
故里飘歌 2020-12-21 12:23

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

// my sample object
var obj = {
    type            : \"Purchase\",
    category        :         


        
相关标签:
1条回答
  • 2020-12-21 12:58

    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)

    0 讨论(0)
提交回复
热议问题