如何循环遍历嵌套对象并删除键值匹配的对象

问题描述 投票:0回答:1

如何循环遍历表单的嵌套对象

{
  '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, CCC, DDD, EEE
键 oldName 的值 = 键 newName 的值

所以,我最终

{
 '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' } 
   } 
}
javascript object
1个回答
0
投票

您可以根据 filter

data 名称字段是否相同来 first
 
last
中的
entries

const data = {
  '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 result = Object.fromEntries(
  Object.entries(data)
    .filter(([_, v]) => v.oldName?.first != v.newName?.first || v.oldName?.last != v.newName?.last)
)

console.log(result)

© www.soinside.com 2019 - 2024. All rights reserved.