user image

Published in : 2022-02-13

Adding an id number at the first index to an array of objects


Now I made an array of objects in JavaScript.

I want to add and id number to each object in the array, at the first index [0]

Here is my code:

const allData= [ { name: "Belly", age: 20 }, { name: "Alfred", age: 58 }, { name: "Sam", age: 10 },]for(const key in allData) { allData[key]['id'] = key;}console.log(allData);

The problem with this code is it returns the id as the last, not the first, index of each object.

Is there a way to acheive my goal? 


Islam Zedan Date : 2022-02-13

You can merge the current object with a new object contains the id so it goes in the first index 

here is my Code :

const allData= [ { name: "Belly", age: 20 }, { name: "Alfred", age: 58 }, { name: "Sam", age: 10 },]for(const key in allData) { allData[key] = Object.assign({id: key}, allData[key]);}console.log(allData);

and there is a fiddle link for it


Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Required to convert Obj {} to Arr [] from key-value pairs using javascript
Publish date: 2022-03-06 | Comments: 2

Tag: Javascript

Can we add a javascript or jQuery to the URL?
Publish date: 2022-03-05 | Comments: 2

Tag: Javascript

Method refactoring to avoid to many npe checks
Publish date: 2022-03-05 | Comments: 0

Tag: Javascript

Check if div have touch another div
Publish date: 2022-03-02 | Comments: 1

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript