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

160
Visualizações
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 Respostas
Responde à pergunta

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