Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
Object: Do not delete existing keys

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);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!