简体   繁体   English

我怎样才能从这个卡片数组中获取“第一个”项目?

[英]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'?如您所见,我想从 cardInfo 数组中获取“Something1”、“Something2”等,如何在 cardInfo 中迭代以显示“卡片”中的每个项目?

 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>

You just need another map method to loop throw the cards property.您只需要另一个map方法来循环抛出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> ${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 class="wrapper"></div>

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.如果您的 CardInfo 数组增长并且您有更多卡片集,则必须再次迭代。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM