Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
In Javascript, when looping through an array of objects, how do I send each element's name to the console?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!