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:
Any guide and help would be appreciated.
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]})