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';
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With