【问题标题】:How to get an item within an object within an array in a map in react [duplicate]如何在反应中获取地图中数组内对象内的项目[重复]
【发布时间】:2023-02-11 03:08:06
【问题描述】:

我目前被困在一个个人项目中,我无法在谷歌中输入正确的词来找到解决方案......

我的代码中有一张来自数据库集合的地图,这张地图显示了一个<Card />,上面有这样的信息:

.map((personnage) => (
    <Card
    key={personnage._id}
    id={personnage._id}
    name={personnage.name}
    job={personnage.job.toLowerCase()}
        firstBounty={personnage.bounties[0]?.toLocaleString()} /*Separate the first bounty with space, the ? is to verify if there is a value, else it won't work*/
    lastBounty={personnage.bounties
            .slice(-1)
            .toLocaleString()} // Separate the last Bounty with space
    firstGrade={personnage.grade[0]?.index}
    lastGrade={personnage.grade.slice(-1)?.index}
/>
))

.json 看起来像

{
  grade: [{ index: 5, name: "something"}, { index: 12, name: "something else"}]
}

所以我试图用slice().reverse().index替换slice(-1).index但是它不起作用......我找不到它背后的逻辑......

所以我只是想获得成绩数组的最后一个成绩。并将 index 传递给 lastGrade 道具。

感谢好心的陌生人的帮助!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以使用数组的 length 来完成此操作。

    你需要减去 1因为数组以索引开头0

    <Card
      ...
      lastGrade={personnage.grade[personnage.grade.length - 1]?.index}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 2022-07-14
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多