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

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

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