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

如何基于OBJECTID找出两个嵌套对象数组的差异?

基于OBJECTID过滤嵌套对象数组的解决方案

我明白你现在的困扰——要从嵌套对象数组里基于OBJECTID做差异过滤,还因为错误的循环写法导致页面崩溃对吧?别担心,咱们用更简洁高效的方法来解决这个问题。

核心思路

  1. 先从geojson数组中提取所有已存在的OBJECTID,存入一个Set(集合的查找效率远高于数组,能避免不必要的性能损耗)
  2. 用filter方法遍历newjson,只保留那些OBJECTID不在上述集合中的项

具体实现代码

let geojson = [ {properties: {OBJECTID: 6249646, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249646, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249648, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249649, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}} ] 
let newjson = [ {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249648, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249649, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249650, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249651, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}} ]

// 提取geojson中所有的OBJECTID到Set里
const existingIds = new Set(geojson.map(item => item.properties.OBJECTID));

// 过滤newjson,只保留不在existingIds中的项
const result = newjson.filter(item => !existingIds.has(item.properties.OBJECTID));

console.log(result);

运行结果

这段代码会输出你期望的结果:

[ {properties: {OBJECTID: 6249650, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, {properties: {OBJECTID: 6249651, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}} ]

为什么之前的for循环会崩溃?

你之前遇到的无限循环大概率是因为循环条件设置错误(比如没有正确递增/递减循环变量),或者是嵌套循环遍历两个数组时时间复杂度太高(O(n*m)),当数组规模大时就会导致页面卡死。而用Set+filter的方式时间复杂度是O(n+m),既简洁又高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:47:49