【问题标题】:Angular2: Filter an array if item included in other other arrayAngular2:如果项目包含在其他其他数组中,则过滤数组
【发布时间】:2018-10-11 20:47:42
【问题描述】:

我正在尝试过滤一个对象数组,以便保留另一个 id 数组中的所有条目。我尝试了不同的方法,但到目前为止没有任何效果。

带有 id 的列表:

list = [1,3]

然后是要过滤的数组:

events= [{id: 1, name: "John"}, {id: 2, name: "Sahra"} ]

我只想保留 id: 1 的条目

【问题讨论】:

  • 您已经尝试了一些方法,介意分享一下您目前正在努力解决的问题或代码吗?
  • 我尝试了过滤器和一些以及过滤器和包含,但我没有将它分配给新变量,因为我认为只使用过滤器会改变数组

标签: arrays angular filter


【解决方案1】:

我希望这是您正在寻找的。只需使用filter & include 方法

const events = [{id: 1, name: "John"}, {id: 2, name: "Sahra"} ]
const list = [1,3]
const result = events.filter(({id}) => list.includes(id))

console.log(result)

【讨论】:

  • 谢谢,这行得通,我几乎已经有了这样的结果,但我认为我可以在数组上使用过滤器,而无需将其分配给新变量。
猜你喜欢
  • 2017-09-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多