简体   繁体   中英

JavaScript Updating a dictionary from array of values using array of keys

I have a dictionary (nested), an array of keys, and an array of values. I need to update the dictionary with the given values using the array of keys as the address. Example:

dict = {"a":{"b":[{"c":1,"d":2},{"c":3,"d":4}]}}  
address = [["a","b",0,"c"],["a","b",1,"d"]]  
value = [10,40]

The desired output is:

dict = {"a":{"b":[{"c":10,"d":2},{"c":3,"d":40}]}}

How can I do this in JavaScript?

You could do something along these lines:

 const dict = {"a":{"b":[{"c":1,"d":2},{"c":3,"d":4}]}}, address = [["a","b",0,"c"],["a","b",1,"d"]], value = [10,40]; // For each address address.forEach((path, index) => { let el = dict; // For each address fragment for (let i = 0; i < path.length; i++) { // If it's not the last fragment if (i < path.length - 1) { // Navigate to the next el = el[ path[i] ]; } else { // Otherwise, set the value el[ path[i] ] = value[index]; } } }); console.log(JSON.stringify(dict));

You could take a function for setting the value and reduce the path to the inner property.

 function setValue(object, [...keys], value) { var last = keys.pop(); keys.reduce((o, k) => o[k], object)[last] = value; } var dict = { a: { b: [{ c: 1, d: 2 }, { c: 3, d: 4 }] } }, address = [["a", "b", 0, "c"], ["a", "b", 1, "d"]], value = [10, 40], i, l = address.length; for (i = 0; i < l; i++) setValue(dict, address[i], value[i]); console.log(dict);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM