数组对象去重(数组每个元素是对象)

本文介绍了一种使用JavaScript的方法来去除数组中的重复项,特别是当数组包含具有相同ID的对象时。该方法利用Map对象来确保每个唯一ID只保留一个条目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:需要将下面这个数组重复项去掉。
let data = [
    {
        "workpiece_id": 1005,
        "workpiece_name": "小板",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1005,
        "workpiece_name": "小板",
        "price": 1828950.64,
        "tax_price": null
    },
    {
        "workpiece_id": 1005,
        "workpiece_name": "小板",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1005,
        "workpiece_name": "小板",
        "price": 7489689.12,
        "tax_price": null
    },
    {
        "workpiece_id": 1005,
        "workpiece_name": "小板",
        "price": 1587068.01,
        "tax_price": null
    },
    {
        "workpiece_id": 1001,
        "workpiece_name": "车件",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1001,
        "workpiece_name": "车件",
        "price": 1078364.6,
        "tax_price": null
    },
    {
        "workpiece_id": 1001,
        "workpiece_name": "车件",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1001,
        "workpiece_name": "车件",
        "price": 33464937.78,
        "tax_price": null
    },
    {
        "workpiece_id": 1001,
        "workpiece_name": "车件",
        "price": 788544,
        "tax_price": null
    },
    {
        "workpiece_id": 1002,
        "workpiece_name": "钣金",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1003,
        "workpiece_name": "大板",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 1003,
        "workpiece_name": "大板",
        "price": 134.4,
        "tax_price": null
    },
    {
        "workpiece_id": 1000,
        "workpiece_name": "机电",
        "price": null,
        "tax_price": null
    },
    {
        "workpiece_id": 997,
        "workpiece_name": "电控",
        "price": null,
        "tax_price": null
    }
]

实现方法:
function removeDuplicate(arr){
	let temp = [];
	cost res = new Map();
	temp =  arr.filter((item) => !res.has(item.workpiece_id) && res.set(item.workpiece_id, 1))
	return temp
}

调用:
console.log(removeDuplicate(data));//[{"workpiece_id":1005,"workpiece_name":"小板","price":null,"tax_price":null},{"workpiece_id":1001,"workpiece_name":"车件","price":null,"tax_price":null},{"workpiece_id":1002,"workpiece_name":"钣金","price":null,"tax_price":null},{"workpiece_id":1003,"workpiece_name":"大板","price":null,"tax_price":null},{"workpiece_id":1000,"workpiece_name":"机电","price":null,"tax_price":null},{"workpiece_id":997,"workpiece_name":"电控","price":null,"tax_price":null}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值