0

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.

1 Answers1

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]})
vsync
  • 118,978
  • 58
  • 307
  • 400
  • Some explanation would make this a better answer. ES6 syntax isn't exactly intuitive. – isherwood Mar 10 '22 at 14:19
  • I want the keys to be in string format. For example "1":{} – Seyed Mahdi Jalali Mar 10 '22 at 14:35
  • This is unnecessarily complex - `{...array}` would do the same- – CherryDT Mar 10 '22 at 14:39
  • @SeyedMahdiJalali That's what this code does... but if you are referring to quotes: they are not part of the object, they are part of the JSON representation. To get a JSON string from an object you can use `JSON.stringify`, but depending on which request library you use, you don't even have to worry about that. – CherryDT Mar 10 '22 at 14:40
  • @SeyedMahdiJalali - the output is exactly as you want. Have you clicked the `run code snippet` button? – vsync Mar 10 '22 at 15:01
  • @CherryDT - Correct. Will also update the answer to include that shortcut available by the language syntax – vsync Mar 10 '22 at 15:03