Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!