如何循环遍历表单的嵌套对象
{
'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' }
}
}
您可以根据 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)