我在下面的对象数组中将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功能实现都将有所帮助。
答案 0 :(得分:5)
您可以使用map
方法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)
您也可以改用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)
答案 1 :(得分:4)
您可以使用Set
并按未知的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; }
答案 2 :(得分:2)
您可以按ID创建一个Map,然后提取值。 [...new Map(test.map(item => [item.id, item])).values()]
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()
])
答案 3 :(得分:1)
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 uniqArray = Array.from(new Map(test.map(e=>[e.id, e])).values());
console.log(uniqArray)
答案 4 :(得分:-1)
使用lodash实用程序库。您可以实现这一目标。 让结果= _.uniqBy(test,'id');