我正在寻找一种简单的方法来删除重复的对象数组



输入:

const data=[
{ id: 123, name: "dave", age: 23 , address:city:"chennai"},
{ id: 456, name: "chris", age: 23, address:city:"delhi"},
{ id: 789, name: "bob", age: 23, address:city:""},
{ id: 789, name: "bob", age: 23, address:city:"mumbai"},
{ id: 555, name: "dave", age: 23 , address:city:"banglore"}
{ id: 101, name: "tom", age: 23, address:city:"jaipur" },
{ id: 101, name: "tom", age: 23, address:city:" " },
{ id: 102, name: "tim", age: 23, address:city:"kolkata"}
]

根据ID值,我需要删除重复对象并覆盖地址键值

例外输出:

const data=[
{ id: 123, name: "dave", age: 23 , address:city:"chennai"},
{ id: 456, name: "chris", age: 23, address:city:"delhi"},
{ id: 789, name: "bob", age: 23, address:city:"mumbai"},
{ id: 555, name: "dave", age: 23 , address:city:"banglore"}
{ id: 101, name: "tom", age: 23, address:city:"jaipur" },
{ id: 102, name: "tim", age: 23, address:city:"kolkata"}
]

我会将其转换为字典,然后再转换回数组。

const data = [{
id: 123,
name: "dave",
age: 23,
"address:city": "chennai"
},
{
id: 456,
name: "chris",
age: 23,
"address:city": "delhi"
},
{
id: 789,
name: "bob",
age: 23,
"address:city": ""
},
{
id: 789,
name: "bob",
age: 23,
"address:city": "mumbai"
},
{
id: 555,
name: "dave",
age: 23,
"address:city": "banglore"
}, {
id: 101,
name: "tom",
age: 23,
"address:city": "jaipur"
},
{
id: 101,
name: "tom",
age: 23,
"address:city": " "
},
{
id: 102,
name: "tim",
age: 23,
"address:city": "kolkata"
}
];
const dataObj = {};
data.forEach(d => {
if (!dataObj[d.id] || d['address:city'].length > dataObj[d.id]['address:city'].length) {
dataObj[d.id] = d;
}
});
const dataWithoutDuplicates = Object.values(dataObj);
console.log(dataWithoutDuplicates);

相关内容

  • 没有找到相关文章

最新更新