You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中根据另一个数组的值过滤对象数组

解决TypeScript数组过滤问题

嘿,这事儿超简单,咱们直接用数组的filter方法搭配includes就能快速搞定!这里给你两种实现方式,按需选用:

基础实现方式

这种方式适合selectedValues元素不多的场景,代码直观易懂:

let userTestStatus: { id: number, name: string }[] = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" },
  { "id": 3, "name": "UnKnown" }
];

const selectedValues = [1, 3];

// 过滤出id在selectedValues中的对象
const filteredUserTestStatus = userTestStatus.filter(user => 
  selectedValues.includes(user.id)
);

console.log(filteredUserTestStatus);
// 输出:[{ "id": 1, "name": "Ready" }, { "id": 3, "name": "UnKnown" }]

性能优化版(适合大数组场景)

如果你的selectedValues元素数量很多,建议先把它转换成Set,因为Set.has()的查找效率是O(1),比数组的includes()(O(n))要快很多:

const selectedSet = new Set(selectedValues);
const filteredUserTestStatus = userTestStatus.filter(user => 
  selectedSet.has(user.id)
);

简单解释一下

  • filter方法会遍历userTestStatus里的每一个对象,返回符合条件的元素组成新数组。
  • 我们的判断条件就是检查当前对象的id是否存在于选中的集合中(不管是数组还是Set)。

这样就能轻松得到你想要的filteredUserTestStatus数组啦!

内容的提问来源于stack exchange,提问作者rumi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:38:34