Home > other >  In Javascript, when looping through an array of objects, how do I send each element's name to t
In Javascript, when looping through an array of objects, how do I send each element's name to t

Time:02-03

How do I spit out the element's name (each object's name) to the console as the array of objects iterates?

I've searched online, in various posts and threads, but I cannot find the answer to this. Nor is there anything on this in the properties/methods for Array that I can see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array.

Here's a simplified example of what I'm trying to do:

let card1 = {
  question:'1 1?',
  answer:'2'
}

let card2 = {
  question:'1 2',
  answer:'3'
}

let card3 = {
  question:'1 3',
  answer:'4'
}

let card4 = {
  question:'1 4',
  answer:'5'
}

let card5 = {
  question:'1 5',
  answer:'6'
}

let cards = [card1,card2,card3,card4,card5];

cards.forEach(function(card){
  console.log(card.name);
  console.log(card.question);
  console.log(card.answer);
});

Here's my fiddle of the above: https://jsfiddle.net/JaredHess/arLmnz72/7/

I keep hoping there's a method like card.name or card.id (but those don't exist).

For example, when it loops to the first element in the array, I want it to show card1, like this:

card1
"1 1?"
"2"

Thank you in advance for your help.

CodePudding user response:

You can define the cards in an array instead of defining them as individual variables.

If you want to create a custom name property for each card, then you certainly can — but if you just want a template name like "name 1", "name 2", etc., then you don't need to define the name in each object in the array. Instead, you can create and add the names in a map function using each card's index, like this:

const cards = [
  {question:'1 1?', answer:'2'},
  {question:'1 2', answer:'3'},
  {question:'1 3', answer:'4'},
  {question:'1 4', answer:'5'},
  {question:'1 5', answer:'6'},
].map((card, index) => ({...card, name: `card${index   1}`}));

cards.forEach(card => console.log(card));

TS Playground

  •  Tags:  
  • Related