Home > Software design >  How can i get the 'first' item from this cards array?
How can i get the 'first' item from this cards array?

Time:07-29

So as you can see I would like to get the 'Something1', 'Something2' etc from cardInfo array, how can I iterate through in cardInfo to display every item from 'cards'?

const cardInfo = [
    {
        name: "Something",
        cards: [
            {
                first: "Something1",
                second: "Something2",
                third: "Something3"
            }
        ]
    }
    
window.addEventListener('DOMContentLoaded', () => {
    const wrapper = document.querySelector('.wrapper');
    let displayCards = cardInfo.map((item) => {
        return `
        <div>
          <h1>${item.name}</h1>
          <div>
            <h2>${item.cards.first}</h2>
            <h2>${item.cards.second}</h2>
            <h2>${item.cards.third}</h2>
          </div>
        </div>`;
    });
    displayCards = displayCards.join("");
    wrapper.innerHTML = displayCards;
});
<div ></div>

CodePudding user response:

You can do that...

for (const key in cardInfo[0].cards[0]) {
  console.log(`${key}: ${cardInfo[0].cards[0][key]}`);
}

But I would recommend you to think about your data structure if you can still change it. If your CardInfo array grows and you have more card sets, you have to iterate again.

const cardInfo = [
  {
    name: 'Something',
    cards: [
      {
        first: 'Something1',
        second: 'Something2',
        third: 'Something3'
      }
    ]
  },
  {
    name: 'Other',
    cards: [
      {
        first: 'Other1',
        second: 'Other2',
        third: 'Other3'
      },
      {
        first: 'Other11',
        second: 'Other22',
        third: 'Other33'
      }
    ]
  }
];

cardInfo.forEach((set) => {
  set.cards.forEach((cardsSet) => {
    for (const key in cardsSet) {
      console.log(`${key}: ${cardsSet[key]}`);
    }
  });
});

CodePudding user response:

You just need another map method to loop throw the cards property.

const cardInfo = [
    {
        name: "Something",
        cards: [
            {
                first: "Something1",
                second: "Something2",
                third: "Something3"
            }
        ]
    }
    ]
    
window.addEventListener('DOMContentLoaded', () => {
    const wrapper = document.querySelector('.wrapper');
    let displayCards = cardInfo.map((item) => {
        return `
        <div>
          <h1>${item.name}</h1>
          ${item.cards.map(({first, second, third}) => {
              return `<div>
            <h2>${first}</h2>
            <h2>${second}</h2>
            <h2>${third}</h2>
          </div>`
           }).join('')}
          
        </div>`;
    });
    displayCards = displayCards.join("");
    wrapper.innerHTML = displayCards;
});
<div ></div>

CodePudding user response:

Wow, thank you so much :) it helped a lot

  • Related