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

158
Vistas
Constructing raw data out of array in javascript

I need to construct API body for using in javascript fetch. The length of array is twenty or so and I need a loop.

I have an array of objects:

[
    {
        name:"x",lname:"y"
    },
    {
        name:"x2",lname:"y2"
    },
]

and this what I want to achieve:

{
    "0":{
        "name":"x",
        "lname":"y"
    },
    "1":{
        "name":"x2",
        "lname":"y2"
    },
}

This is raw in postman body:

enter image description here

Any guide and help would be appreciated.

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

0

Converting an Array to an Object is easily done with Array.reduce and using the index argument as the key of the properties:

const data = [
    {name:"x",lname:"y"},
    {name:"x2",lname:"y2"},
]

console.log( 
  data.reduce((acc, item, i) => ({...acc, [i]:item}) ,{})
)

Or shorter, as suggested by @CherryDT (in the comments below), which automatically converts the Array to an Object consisting of keys derived from the array's items' indices:

const data = [
    {name:"x",lname:"y"},
    {name:"x2",lname:"y2"},
]

console.log({...data})

Tip: If you want the keys indices to start from 1 and not 0, do:

console.log({...[,...data]})
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