Home > database >  How to add a new property with index value to an object array in JavaScript?
How to add a new property with index value to an object array in JavaScript?

Time:05-02

I am new to the forum and a beginner at JavaScript. Please look at my code below that I am facing a problem with in terms of the output -

let myColor = ["Red", "Green", "White", "Black"];
console.log(myColor.toString());
console.log(myColor.join(" "));
let strings = ["avengers", "captain america", "ironman", "black panther"];
const newStrings = strings.map(elements => { 
    return elements.toUpperCase()}
);
console.log(newStrings);

const heroes = [
    {name: "Spider-Man"},
    {name: "Thor"},
    {name:"Black Panther"},
    {name: "Captain Marvel"},
    {name: "Silver Surfer"}
];

heroes.forEach(function(o) {
  o.hero = o.name;
  delete o.name;
});

let heroesName = [];
for(var i=0; i<heroes.length; i  ) {
    heroesName.push(heroes[i]); heroesName[i].id=i;
};
console.log(heroesName);

const inputWords = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
console.log(inputWords.splice(3,5));

With the above-mentioned code I am getting the below-mentioned output -

Red,Green,White,Black
Red Green White Black
[ 'AVENGERS', 'CAPTAIN AMERICA', 'IRONMAN', 'BLACK PANTHER' ]
[
  { hero: 'Spider-Man', id: 0 },
  { hero: 'Thor', id: 1 },
  { hero: 'Black Panther', id: 2 },
  { hero: 'Captain Marvel', id: 3 },
  { hero: 'Silver Surfer', id: 4 }
]
[ 'exuberant', 'destruction', 'present' ]

However, I am trying to get the output as follows -

Red,Green,White,Black
Red Green White Black
[ 'AVENGERS', 'CAPTAIN AMERICA', 'IRONMAN', 'BLACK PANTHER' ]
[
  { id: 0, hero: 'Spider-Man' },
  { id: 1, hero: 'Thor' },
  { id: 2, hero: 'Black Panther' },
  { id: 3, hero: 'Captain Marvel' },
  { id: 4, hero: 'Silver Surfer' }
]
[ 'exuberant', 'destruction', 'present' ]

What is it that I am doing wrong over here? So, all I want is the ID property in the object array called heroes to be before the hero name and not after. Could someone guide me?

CodePudding user response:

It doesn't matter what order the properties are in. Still if you want to change the order, you can change a line in your for loop

let heroesName = [];
for(let i=0; i<heroes.length; i  ) {
       heroesName.push({ id: i, hero: heroes[i].hero });
};
console.log(heroesName);

  • Related