3

I have a javascript object;

xml
-nutrition
--daily values
--food
---0
----fat=20g
----sodium=
---1
----fat=20g
----sodium=5mg
---2
----fat=20g
----sodium=5mg
-stores
--0
--1

I also have a dynamically generated javascript array

["xml", "nutrition", "food", 0]

How can I update the javascript object based on this array? without typing it manually

myobj[array[0]][array[1]][array[2]][array[3]].fat = '30g';

1 Answer 1

6

You could use Array#reduce() for it.

It iterates over all given keys and returns the last reference for further use.

["xml", "nutrition", "food", 0].reduce(function (r, k) {
    return r[k];
}, myobj).fat = '30g';

or ES6

["xml", "nutrition", "food", 0].reduce((r, k) => r[k], myobj).fat = '30g';
Sign up to request clarification or add additional context in comments.

Comments

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.