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

如何在JavaScript对象数组中删除refId不匹配数组内id且非null的对象

过滤JavaScript对象数组:保留refId为null或refId匹配数组内id的对象

需求说明

处理对象数组时遵循以下规则:

  • 保留所有refId为null的对象
  • 若refId不为null,仅当该refId值能匹配数组中任意对象的id时,才保留该对象
  • 删除refId不为null且无对应匹配id的对象

示例输入

[
  {id: 1 , refId:null, name:'jhon'},
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'}, 
  {id: 5 , refId:16, name:'ram'}, 
  {id: 6 , refId:15, name:'nam'}
]

期望输出

[
  {id: 1 , refId:null, name:'jhon'}, 
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'},
]

解决方案

高效实现(适合大数据量)

先把数组中所有id提取到Set中(查找效率为O(1)),再用filter方法筛选:

const input = [/* 你的输入数组 */];

// 收集所有存在的id到Set
const existingIds = new Set(input.map(item => item.id));

// 过滤数组
const filteredArray = input.filter(item => {
  return item.refId === null || existingIds.has(item.refId);
});

console.log(filteredArray);

简洁实现(适合小数据量)

如果数组规模不大,也可以直接用some方法判断是否存在匹配的id:

const input = [/* 你的输入数组 */];

const filteredArray = input.filter(item => {
  return item.refId === null || input.some(i => i.id === item.refId);
});

console.log(filteredArray);

效果验证

两种实现都会输出你期望的结果。第一种用Set优化了查找性能,数组元素较多时优势明显;第二种代码更简洁,适合小规模数据场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:20:34