Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i get the 'first' item from this cards array?

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 class="wrapper"></div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]}`);
    }
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading