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';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.