-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

10
  • Does this answer your question? Convert Array to Object Commented Apr 23, 2021 at 9:40
  • 1
    @poPaTheGuru not the same Commented Apr 23, 2021 at 9:41
  • I want the keys to be "id" not numbers Commented Apr 23, 2021 at 9:42
  • 1
    @Jacquesジャック Doesn't work, you're not returning anything from the block Commented Apr 23, 2021 at 9:43
  • 2
    Please be aware that the input and output data is not JSON. Commented Apr 23, 2021 at 9:44

3 Answers 3

2

Try the map function

jsonObjectArray = jsonArray.map((ele) => {return {"id": ele}})
Sign up to request clarification or add additional context in comments.

Comments

1

You can use map.

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.