Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

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

7 months 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.

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.