-2

I have this code

const jsonArray = [1,2,3,4,5];

I want to convert it so I can get

{
 "id" : 1
},
{
 "id" : 2
},
{
 "id" : 3
},
{
 "id" : 4
},
{
 "id" : 5
}

So I need to add "id" key for all the objects outputs

Tamer Essam
  • 51
  • 1
  • 6

3 Answers3

2

Try the map function

jsonObjectArray = jsonArray.map((ele) => {return {"id": ele}})
Shubham Periwal
  • 2,198
  • 2
  • 8
  • 26
1

You can use map.

jsonArray.map(id=>({id}))
1

You could use Array.prototype.map() for that:

const jsonArray = [1,2,3,4,5];
        
const arrayofObjects = jsonArray.map(e => ({id: e}))

console.log(arrayofObjects);
Andy
  • 61,948
  • 13
  • 68
  • 95