Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

297
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda