Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

299
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda