Hi have the following code snipped. (Javascript create Object by array The problem is, this will delete my existing key, but i want to keep and update them. Only if the key not exists, then should add it.
function setValueToLightGroup(Group, keys, value) {
let c=Group;
keys = keys.split('.');
for (var i=0; i<keys.length-1; ++i) c = c[keys[i]] = {};
c[keys[i]] = value;
}
setValueToLightGroup(LightGroups[`FlurEG`], 'autoOff.timers.startTimer', 300);
setValueToLightGroup(LightGroups[`FlurEG`], 'autoOff.enabled', true);
setValueToLightGroup(LightGroups[`FlurEG`], 'power', true);
The general problem is that you overwrite the previous value of c[keys[i]]
in every iteration of the for
loop with {}
. If you want to keep the previous contents, please only overwrite the contents if the key does not exist.
for (let i = 0; i < keys.length - 1; i++) {
if (!(keys[i] in c)) { // <-- this check avoids that value is overwritten
c[keys[i]] = {};
}
c = c[keys[i]];
}
As noted in the comments, an alternative would be using ??=
for the assignment. It performs the assignment if the left hand side is undefined.