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

164
Visualizações
Nested Object Loop in JS

I'm trying to add a series of values to a nested object, having some trouble with the loop in the following code. Any help would be really appreciated.

let settings = {};

function write(id, values) {
    if(!settings[id]) settings[id] = {};
    for(var x = 0; x < Object.keys(values).length; x ++) {
        settings[id][values[x]] = values[values[x]];
    }
}

//example
write('example', {'prop1': 5, 'prop2': 10});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You're attempting to index the object values with x, which is a number. To loop through the keys of your object you can use a for...in loop:

function write(id, values) {
    if(!settings[id]) settings[id] = {};
    for(const key in values) {
        settings[id][key] = values[key];
    }
}

Another approach would be to use object destructuring:

function write(id, values) {
    settings[id] = { ...(settings[id] || {}), ...values };
}
about 4 years ago · Juan Pablo Isaza Relatório

0

values is an object. Accessing values[x] will return undefined.

You have to access it with the correct keys in that object as below.

let settings = {};

function write(id, values) {
  if (!settings[id]) settings[id] = {};
  const keys = Object.keys(values);
  for (var x = 0; x < keys.length; x++) {
    settings[id][keys[x]] = values[keys[x]];
  }
  console.log(settings)
}

//example
write('example', { 'prop1': 5, 'prop2': 10 });

about 4 years ago · Juan Pablo Isaza Relatório

0

try to keep the Object.keys(values) return in another variable and use it to assign value in setting like this

function write(id, values) {
    if(!settings[id]) settings[id] = {};
    const key = Object.keys(values) 
    for(var x = 0; x < key.length; x ++) {
        settings[id][key[x]] = values[key[x]];
    }
}
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