我有这样的事情:
items: { _id: number; place: SomeAddressClassDto }[] = [];
sessionItem: { _id: number; place: SomeAddressClassDto };
createAddressList() {
this.service.getWorkingPlaces().subscribe((items) => {
this.items = items;
this.sessionItem = {
place: JSON.parse(sessionStorage.getItem('currentPlace')),
_id: this.items.length,
};
this.items.push(this.sessionItem);
// _.uniqBy(this.items, 'place')
const idx = items.findIndex((item) => this.service.comparePlaces(item.place,
this.service.getCurrentWorkingPlace()));
if (idx !== -1) this.radiobox.option = `${idx}`;
});
}
我正在尝试使用 _uniqBy 方法从“items”数组中删除任何重复项,但它不起作用。我认为这是因为对于这个 items._id 总是不同的但 items.place 可以是平等的,如果是我想摆脱这个。
也许更好的方法是检查相同的 items.place 是否已经在该数组中,但不知道如何执行此操作。
编辑:更详细地说,项目如下所示:
0: place: {name, street, city, etc...}
_id: 0
因此,可能有非常相似的对象,而它们的不同之处仅在于一个属性的位置{}
我建议使用_id
来确定该值是否唯一。如果您使用place
该值可能始终是唯一的,因为它们可能是同一类的不同实例。(如果是这种情况,我无法从您的代码中看出)
createAddressList() {
this.service.getWorkingPlaces().subscribe((items) => {
this.items = items;
this.sessionItem = {
place: JSON.parse(sessionStorage.getItem('currentPlace')),
_id: this.items.length,
};
this.items.push(this.sessionItem);
_.uniqBy(this.items, '_id');
const idx = items.findIndex((item) => this.service.comparePlaces(item.place, this.service.getCurrentWorkingPlace()));
if (idx !== -1) {
this.radiobox.option = `${idx}`;
}
});
}
或者,您可以使用内部的属性place
来确定它们是否是唯一的,如下所示:
_.uniqBy(this.items, (x) => x.place && x.place.someOtherPropertyInsideOfPlace);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句