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

230
Visualizações
JS: transform header and body array to single json

I want to transform 2 arrays into 1 final json object. The first array contains the header data and the second one the body. Each row of the body should be assigned to a column of the header. This image illustrates the input and the expected output:

enter image description here

I'm using 3 nested loops to assign the data. The keys are working but I'm stucked getting the correct data because somehow only data from the last body row are extracted.

There must be a minor thing, I'm missing in my code:

const header = ['A','B','C','D']
const body = [
  ["A1","A2","A3","A4","A5","A6"],
  ["B1","B2","B3","B4","B5","B6"],
  ["C1","C2","C3","C4","C5","C6"],
  ["D1","D2","D3","D4","D5","D6"],
];

const json = [];

for (let y = 0; y < body[0].length; y++)
{
  const line = {};
  for(const hl of header)
  {
    for(const bo of body)
    {
      line[hl] = bo[y];
    }
  } 
  json.push(line);
}

console.log(json);

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

0

I'd say your gut feeling is correct, but you're always replacing the column values with the values of the last column.

Plus, at least as I understand your drawing, you want an array of objects, where the key is the header and the value is the corresponding value, i.e. I understand you want [{A:'A1', B: 'B1', C: 'C1', D: 'D1'}, …] and not [['A1', 'B1', 'C1', 'D1'], …]. Correct?

Below is an approach using [].map() and [].reduce(), which, to me (who is used to this style of writing, I admit), makes it a lot clearer what happens:

const header = ['A','B','C','D']
const body = [
  ["A1","A2","A3","A4","A5","A6"],
  ["B1","B2","B3","B4","B5","B6"],
  ["C1","C2","C3","C4","C5","C6"],
  ["D1","D2","D3","D4","D5","D6"],
];

console.log(body[0].map((_, row) =>
  header.reduce((json, key, col) => ({
    ...json,
    [key]: body[col][row]
  }), {})));

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