提问者:小点点

如何使用扩散算子从对象阵列中删除重复项


我有以下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功能实现都会有所帮助。


共3个答案

匿名用户

您可以使用find方法将对象映射回对象数组,这将返回第一个具有该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)

匿名用户

您可以使用集合并按未知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: "" }],
    unique = test.filter((s => ({ id }) => !s.has(id) && s.add(id))(new Set));
    
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

匿名用户

您可以按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: ""}]

console.log([
  ...new Map(test.map(item => [item.id, item])).values()
])