Dev-Mo
13 Feb 2022
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?
Islam Zedan
13 Feb 2022
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
© 2024 Copyrights reserved for web-brackets.com