Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a javascript object using an array for reference

Tags:

javascript

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';
like image 407
Colin Palmer Avatar asked Mar 31 '26 20:03

Colin Palmer


1 Answers

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';
like image 101
Nina Scholz Avatar answered Apr 03 '26 09:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!