I have a bunch of JSON with multiple objects, arrays, strings, booleans, numbers etc. which are stored in one object at the root level and component.
Here is a sample:
Below is a simple version of Nina's answer (the one using reduce).
Hope this helps you get what's going on behind that.
const setValueByPathArray = (object, path, value) => {
let i = 0
let reference = object
while (i < path.length - 1) {
const currentPath = path[i]
reference = reference[currentPath]
i += 1
}
const lastPath = path[path.length - 1]
reference[lastPath] = value
return object
}
const config = { theme: { auto: { sensor: "sensor.sn1_ldr", below: 600 }, ui: { cards: { round: false, elevation: 1 } } } }
const path = ["theme", "auto", "sensor"];
setValueByPathArray(config, path, 'foo')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Use recursion to loop through.
const object1 = {
"theme": {
"auto": {
"sensor": "sensor.sn1_ldr",
"below": 600
},
"ui": {
"cards": {
"round": false,
"elevation": 1
}
},
},
}
var result = [];
see(object1);
console.log(result);
function see (obj){
var k = Object.keys(obj)
for (var i = 0; i < k.length; i++){
result.push(k[i]);
if (obj[k[i]] instanceof Object){
see(obj[k[i]]);
}
}
}
You could store the last key and reduce the object by taking the keys from the path.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var config = { theme: { auto: { sensor: "sensor.sn1_ldr", below: 600 }, ui: { cards: { round: false, elevation: 1 } } } },
path = ["theme", "auto", "sensor"];
setValue(config, path, 'foo');
console.log(config);
.as-console-wrapper { max-height: 100% !important; top: 0; }