【问题标题】:Iterate through a prop, but sort by a different prop React JS遍历一个 prop,但按不同的 prop React JS 排序
【发布时间】:2019-09-18 15:46:30
【问题描述】:

我有这个按缺陷(字符串)对数组进行排序的函数,但是,我想遍历计数(数字)。

getCount() {

let arr = this.state.rows
  let arr2 = arr.filter(qc => qc.BinsByDayByOrchardsQCs.length > 0).map((qc) =>
      qc.BinsByDayByOrchardsQCs.map((qc2) =>
          qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3).sort((a, b) 
              => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0)));

        return arr2
    };

这个函数返回

0: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Bruise", Count: 2, BinsByDayByOrchardsQCs: null}
1: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Hail damage", Count: 0, BinsByDayByOrchardsQCs: null}
2: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Scuff", Count: 2, BinsByDayByOrchardsQCs: null}
3: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Sunburn", Count: 1, BinsByDayByOrchardsQCs: null}

我的数组已排序,但是在我的原始函数中,我想遍历 Count,而不是整个对象。

它看起来像这样..

 qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3.Count).sort((a, b) 
               => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0)));

但我目前收到“类型‘数字’上不存在属性‘缺陷’

还应该注意的是,我将 TypeScript 与 React 一起使用

我的界面
BinsByDayByOrchardsQCs: { BinsByDayByOrchardsQCsDefects: { Defect: string, Count: number }[] }[]

【问题讨论】:

  • 您希望您的getCount 函数在进行您计划的更改之后返回什么?
  • 我希望它返回计数,但按缺陷排序

标签: javascript arrays reactjs typescript sorting


【解决方案1】:

您收到此错误的原因是,当您使用 map 时,它实际上会输出一个仅包含 count 值的数组

qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3.Count)

输出:

[2, 0, 2 , 1]

你应该先排序再映射,换一种方式试试:

qc2.BinsByDayByOrchardsQCsDefects.sort((a, b) => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0))).map((qc3) => qc3.Count);

此外,您在这里对字符串进行排序,所以我不确定这是否会正常工作,但至少您不应该收到有关该属性不存在的错误。

更新:

我在你的帖子中错过了你正在使用 Typescript,试试这个看看它是否按照this post 的建议工作

qc2.BinsByDayByOrchardsQCsDefects.sort((a, b) => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0))).map((qc3) => (qc3 as any).Count);

另一个建议是尝试使用qc3["Count"] 而不是qc3.Count,Typescript 不知何故不能平等地看待这件事......

【讨论】:

  • 当你运行这个qc2.BinsByDayByOrchardsQCsDefects.sort((a, b) =&gt; a.Defect &lt; b.Defect ? -1 : a.Defect &gt; b.Defect ? 1: 0)))时你会得到什么输出
  • 我的 OP 中的相同输出
  • 帮我理解一下为什么在定义 arr2 时返回 arr2?
  • 另外你创建一个 fiddleJS 会更容易帮助你调试
  • 好吧,如果我不返回 arr2 那么它是未定义的......将无法使用 jsFiddle..我正在从本地数据库中检索数据
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2017-10-15
  • 2019-06-23
相关资源
最近更新 更多