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

169
Visualizações
Moving variables in nested Loop JavaScript

function transformEmployeeData(employeeData) {
  var arr = [];
  var obj = {};
  for (var i = 0; i < employeeData.length; i++) {

    var personArr = employeeData[i];
    for (var j = 0; j < personArr.length; j++) {
      var key = personArr[j][0];
      var value = personArr[j][1];
      obj[key] = value;
    }
    arr.push(obj);
  }
  return arr;
}

input = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

var getData = transformEmployeeData(input);
console.log(getData);

And I want my result to be like this:

[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

So I moved var obj = {}; into the first for loop, and I got the right result. But I still cannot figure out why I have to move it inside the loop? what is the difference? Please help, thank you!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If you don't put it in the loop, you are defining a single object and are just modifying its contents within the loop body and pushing that single object into the array.

But, if you include it inside the loop, you create a new object each time the loop body executes (and the existing variable stops pointing to the previous object and now references the new one) and then push that new object into the array, resulting in multiple objects in your output.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you do not add the object in the first loop, you are creating a single object for the whole function execution which can override previous properties of the first loop by the second one

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use map and Object.fromEntries for that

function transformEmployeeData(employeeData) {
 return employeeData.map(Object.fromEntries)
}

input = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

var getData = transformEmployeeData(input);
console.log(getData);

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