Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda