user image

Dev-Mo
Published in : 2022-02-13

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

Javascript

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? 

Comments

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

https://jsfiddle.net/pdzeu906/1/

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

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

Coping plain text into form bug.
Publish date: 2022-02-11 | Comments: 1

Tag: Javascript

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

Tag: Javascript

JavaScript variable for Changing CSS Height
Publish date: 2022-02-12 | Comments: 1

Tag: Javascript

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

Tag: Javascript

How can I switch between two background-colors using js setinterval( )
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript