gpt4 book ai didi

javascript - 如何使用展开运算符从对象数组中删除重复项

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:05 27 4
gpt4 key购买 nike

我有以下对象数组,其中 id 作为唯一键":

var test = [
{id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},
{id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id: 3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}
]

由此我想使用扩展运算符检索唯一对象,我尝试使用以下代码:

const uniKeys = [...(new Set(test.map(({ id }) => id)))];

我只能检索 ID,如何使用扩展运算符检索唯一对象。此外,任何新的 ES6 功能实现都会有所帮助。

最佳答案

您可以使用find 方法map 返回对象数组,这将返回具有该id 的第一个对象。

var test = [{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}]
var uniq = [...new Set(test.map(({id}) => id))].map(e => test.find(({id}) => id == e));
console.log(uniq)

您也可以使用 filter 方法。

var test = [{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}]

var uniq = test.filter(function({id}) {
return !this[id] && (this[id] = id)
}, {})

console.log(uniq)

关于javascript - 如何使用展开运算符从对象数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51741910/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com