如何对比两个对象数组,提取前者中后者缺失的objectType属性
解决方案
可以通过以下步骤高效提取目标值:
- 先提取
arrayTwo中所有的objectType并存储到Set中(利用Set的O(1)查找效率提升性能) - 遍历
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
相关产品推荐
相关产品推荐

