Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda