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

179
Vistas
creating array of objects from an array of arrays

I have this array

[
  [ [ 'id', 'name' ], [ '1', 'A' ] ],
  [ [ 'id', 'name' ], [ '2', 'B' ] ],
  [ [ 'id', 'name' ], [ '3', 'C' ] ]
] 

and i want it to be array of object with the corresponding value

[{id: 1, name: 'A'}, {id:2, name: 'B'}, {id:3, name: 'C'}]

thank you

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use any higher-order functions in js like map, for, reduce. Below is the implementation with Array.reduce

const arr = [
 [
   ['id', 'name'],
   ['1', 'A'],
 ],
 [
   ['id', 'name'],
   ['2', 'B'],
 ],
 [
   ['id', 'name'],
   ['3', 'C'],],
 ];


const response = arr.reduce((acc, curr) => {
   const [firstItem, secondItem] = curr;
   const [id, name] = firstItem;
   const [val1, val2] = secondItem;
   acc.push({ [id]: val1, [name]: val2 });
   return ACC;
}, []);

console.log(response)
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could transpose the inner arrays and map new objects.

const
    transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
    data = [[['id', 'name'], ['1', 'A'] ], [['id', 'name'], ['2', 'B']], [['id', 'name'], ['3', 'C']]],
    result = data.map(a => Object.fromEntries(a.reduce(transpose, [])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Using Array#map iterate over the array.

For every subarray, it will have a list of keys and a list of values. Using Array#reduce, you can iterate over keys to compute an object with the help of the third parameter, the index, to get each corresponding value:

const data = [
  [ [ 'id', 'name', 'age' ], [ '1', 'A', 22 ] ],
  [ [ 'id', 'name' ], [ '2', 'B' ] ],
  [ [ 'id', 'name' ], [ '3', 'C' ] ]
];

const arr = data.map(([ keys, values = [] ]) => 
  keys.reduce((obj, key, i) => ({ ...obj, [key]: values[i] }), {})
);

console.log(arr);

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