如何根据所有位置的 LocId return 对象唯一?
How to return objects unique based on LocId from all location?
我正在研究 angular 7 我遇到问题:我无法 return 基于 LocId 的不同或唯一对象。
我需要 return 对象数组中所有位置的唯一对象。
allLocations:any[]=[];
ngOnInit()
{
this.locationsService.allLocations.forEach(loc => {
let d = this.locationsService.allLocations.findIndex(x => x.Locid == loc.Locid);
if (d !== -1) {
this.locationsService.allLocations.splice(d, 1);
}
和 html 组件代码如下:
<tr *ngFor="let l of locationsService.allLocations">
<td class="z2-boxstyle1-td-colcontent">
<div> {{l.Locid}} </div>
</td>
</tr>
数组的结果是:
[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]
因为 Locid 在两个对象上是相同的,所以我 return 不同,它必须如下所示:
预期结果:
[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]
原因是,.splice
元素在数组中的顺序会立即发生变化。
您的意图看起来只是不想重复这些值。
你可以使用 .reduce
:
做这样的事情
var res = this.locationsService.allLocations.reduce((a,v)=>{
if(!a[v.Locid]){
a[v.Locid] = v;
}
return a
},{});
console.log(Object.values(res));
或者您可以只取一个空列表,只要在此列表中找不到任何元素的 Locid
,就继续从 this.locationsService.allLocations
中推送值。 (2 遍)
或者,您可以使用 .filter
和 .findIndex
来完成这项工作。 (2 遍)
但是,我 不 推荐这些方法,因为它们需要两次传递,.reduce
一次传递会表现更好。
您可以按 Locid 筛选
var newArr = arr.filter((x, index, self) =>
index === self.findIndex((t) => (t.Locid === x.Locid )));
console.log(newArr);
我正在研究 angular 7 我遇到问题:我无法 return 基于 LocId 的不同或唯一对象。
我需要 return 对象数组中所有位置的唯一对象。
allLocations:any[]=[];
ngOnInit()
{
this.locationsService.allLocations.forEach(loc => {
let d = this.locationsService.allLocations.findIndex(x => x.Locid == loc.Locid);
if (d !== -1) {
this.locationsService.allLocations.splice(d, 1);
}
和 html 组件代码如下:
<tr *ngFor="let l of locationsService.allLocations">
<td class="z2-boxstyle1-td-colcontent">
<div> {{l.Locid}} </div>
</td>
</tr>
数组的结果是:
[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]
因为 Locid 在两个对象上是相同的,所以我 return 不同,它必须如下所示:
预期结果:
[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]
原因是,.splice
元素在数组中的顺序会立即发生变化。
您的意图看起来只是不想重复这些值。
你可以使用 .reduce
:
var res = this.locationsService.allLocations.reduce((a,v)=>{
if(!a[v.Locid]){
a[v.Locid] = v;
}
return a
},{});
console.log(Object.values(res));
或者您可以只取一个空列表,只要在此列表中找不到任何元素的 Locid
,就继续从 this.locationsService.allLocations
中推送值。 (2 遍)
或者,您可以使用 .filter
和 .findIndex
来完成这项工作。 (2 遍)
但是,我 不 推荐这些方法,因为它们需要两次传递,.reduce
一次传递会表现更好。
您可以按 Locid 筛选
var newArr = arr.filter((x, index, self) =>
index === self.findIndex((t) => (t.Locid === x.Locid )));
console.log(newArr);