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

如何对比两个对象数组,提取前者中后者缺失的objectType属性

解决方案

可以通过以下步骤高效提取目标值:

  1. 先提取arrayTwo中所有的objectType并存储到Set中(利用Set的O(1)查找效率提升性能)
  2. 遍历arrayOne,筛选出objectType不在上述Set中的元素,再提取对应的objectType值

代码实现(JavaScript)

const arrayOne = [{objectType: 'License', objectName: 'Test Object 1'},
            {objectType: 'Owner', objectName: 'Test Object 2'},
            {objectType: 'Location', objectName: 'Test Object 3'},
            {objectType: 'Job', objectName: 'Test Object 6'}]
        
const arrayTwo = [{objectType: 'License', objectName: 'Test Object 1', dataType: 'String'},
            {objectType: 'Owner', objectName: 'Test Object 2', dataType: 'Value List'},
            {objectType: 'Prop', objectName: 'Test Object 5', dataType: 'Number'}]

// 提取arrayTwo的所有objectType到Set
const existingTypes = new Set(arrayTwo.map(item => item.objectType));

// 筛选并提取arrayOne中不存在于arrayTwo的objectType
const missingTypes = arrayOne
  .filter(item => !existingTypes.has(item.objectType))
  .map(item => item.objectType);

console.log(missingTypes); // 输出: ["Location", "Job"]

额外说明

  • 如果arrayOne中存在重复的objectType,可以通过[...new Set(missingTypes)]对结果去重,确保每个值唯一。
  • 使用Set而非数组存储arrayTwo的类型,是因为当数组规模较大时,Set的查找速度远快于数组的includes方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:55:19