4

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?

2
  • Capitalization? "Apartment" != "apartment" Commented Jun 16, 2017 at 13:42
  • @corn3lius oh its a typo in writing the question. my problem still exist. i will update the question. Commented Jun 16, 2017 at 13:44

1 Answer 1

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I included an undefined check, now it will return the object where the error occured.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.