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

如何遍历嵌套对象并删除oldName与newName值匹配的子对象

处理嵌套对象:移除oldName与newName相等的条目

原始对象

{
  'AAA': 
   { oldName: { index: 0, first: 'Bob', last: 'Hanson' },
     newName: { index: 0, first: 'Bob', last: 'Hanson' }
   }, 
  'BBB': 
   { oldName: { index: 1, first: 'Velma', last: 'Jones' },
     newName: { index: 2, first: 'Velma', last: 'Roberts'} 
   },
  'CCC': 
   { oldName: { index: 2, first: 'Jou', last: 'Xi' },
     newName: { index: 3, first: 'Jou', last: 'Xi' } 
   },
  'DDD': 
   { oldName: { index: 3, first: 'Betty', last: 'Ford' },
     newName: undefined},
  'EEE': 
   { oldName: undefined,
     newName: { index: 1, first: 'Fred', last: 'Tree' } 
  } 
}

需求说明

遍历上述对象,删除所有一级键(如AAA、BBB)下oldName与newName值完全相等的嵌套对象,保留两者不相等或其中一方为undefined的条目。

解决方案代码

// 定义比较函数,处理undefined和对象相等判断
function isEqual(a, b) {
  // 两者都为undefined则判定相等
  if (a === undefined && b === undefined) return true;
  // 仅一方为undefined则判定不相等
  if (a === undefined || b === undefined) return false;
  // 针对固定结构的对象,用JSON.stringify快速比较内容一致性
  return JSON.stringify(a) === JSON.stringify(b);
}

// 过滤目标对象的核心函数
function filterTargetObj(originalObj) {
  const filteredResult = {};
  // 遍历原始对象的每个键值对
  for (const [key, item] of Object.entries(originalObj)) {
    const { oldName, newName } = item;
    // 若oldName和newName不相等,则保留该条目
    if (!isEqual(oldName, newName)) {
      filteredResult[key] = item;
    }
  }
  return filteredResult;
}

// 原始数据
const originalData = {
  'AAA': { oldName: { index: 0, first: 'Bob', last: 'Hanson' }, newName: { index: 0, first: 'Bob', last: 'Hanson' } },
  'BBB': { oldName: { index: 1, first: 'Velma', last: 'Jones' }, newName: { index: 2, first: 'Velma', last: 'Roberts' } },
  'CCC': { oldName: { index: 2, first: 'Jou', last: 'Xi' }, newName: { index: 3, first: 'Jou', last: 'Xi' } },
  'DDD': { oldName: { index: 3, first: 'Betty', last: 'Ford' }, newName: undefined },
  'EEE': { oldName: undefined, newName: { index: 1, first: 'Fred', last: 'Tree' } }
};

// 执行过滤并输出结果
const finalResult = filterTargetObj(originalData);
console.log(finalResult);

最终结果

{
 'BBB': 
   { oldName: { index: 1, first: 'Velma', last: 'Jones' },
     newName: { index: 2, first: 'Velma', last: 'Roberts' } 
   },
  'DDD': 
   { oldName: { index: 3, first: 'Betty', last: 'Ford' },
     newName: undefined },
  'EEE': 
   { oldName: undefined,
     newName: { index: 1, first: 'Fred', last: 'Tree' } 
   } 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:22:50