【问题标题】:objects sequence change with array filter method (Javascript)使用数组过滤方法(Javascript)更改对象序列
【发布时间】:2021-02-22 01:16:05
【问题描述】:

我有以下名为getRecommendations 的对象数组。我将使用它来映射我将从后端接收的数据。

const getRecommendations = [
 { 
  recoTitle: "Retire",
  recoDescription: "Its time to retire and relax with family"
 },
 {
  recoTitle: "Buy home",
  recoDescription: "Start saving to buy home in near future"
 }
]

以下是我从后端收到的一系列建议,它按排名顺序排列。例如在这种情况下,Buy home 是排名 1,Retire 是排名 2。有时它可能是其他方式。我想按照从后端到 UI 显示的顺序显示推荐。

const recommendations = ["Buy home", "Retire"];

但我做了以下映射,因为我不仅需要recoTitle,还需要recoDescription 来显示用户。我有getRecommendations,它映射了recoTitle 和recoDescription。下面的代码用于在对象数组中获取两者。如下

const filteredReco = getRecommendations.filter(
  ({ recoTitle}) => recoDetails && recoDetails.indexOf(recoTitle) !== -1,
);

现在,如果我通过控制台日志看到filteredReco 的内容,Retire 将作为第一个对象出现,然后是Buy Home。我如何确保列表顺序不受我使用过滤器的方式的影响。有人可以建议吗。

【问题讨论】:

  • 这是因为您正在迭代 getRecommendations,并且序列基于此。如果要保持推荐中的顺序,则需要重写逻辑以循环遍历推荐数组中的每个项目并从 getRecommendations 中获取匹配的 obj
  • recommendations.map(recName => getRecommendations.find(rec => rec.recoTitle === recName)) 是这样的吗?
  • @igk- 是的,这行得通。谢谢。您也可以将其发布为答案。可能会帮助某人
  • 是的,当然。编码愉快!

标签: javascript arrays reactjs object filter


【解决方案1】:
recommendations.map(recName =>  
   getRecommendations.find(rec => rec.recoTitle === recName)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-15
    • 2022-10-14
    • 2021-10-16
    • 2017-10-19
    • 2019-01-22
    • 2014-08-14
    相关资源
    最近更新 更多