我正在寻找一种简单的方法来删除重复的对象数组 [重复]
Posted
技术标签:
【中文标题】我正在寻找一种简单的方法来删除重复的对象数组 [重复]【英文标题】:I'm looking for a simple methodology to remove duplicate array of object [duplicate] 【发布时间】:2021-11-03 07:14:32 【问题描述】:输入:
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"
]
【问题讨论】:
您不想删除重复项,但也想合并。但是也有一些错误,例如address:city:"chennai"
这不是有效的语法。
【参考方案1】:
我会通过将其转换为字典然后再转换回数组来做到这一点。
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);
【讨论】:
以上是关于我正在寻找一种简单的方法来删除重复的对象数组 [重复]的主要内容,如果未能解决你的问题,请参考以下文章