【问题标题】:How to return objects unique based on LocId from all location?如何从所有位置返回基于 LocId 的唯一对象?
【发布时间】:2020-11-02 01:21:20
【问题描述】:

我在 Angular 7 上工作,我遇到问题:我无法根据 LocId 返回不同或唯一的对象。

我需要从所有位置的对象数组中返回唯一的对象。

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 相同,所以我返回不同的,它必须如下:

预期结果:

[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]

【问题讨论】:

  • 感谢您的回复,但我在 html 上使用了这样的位置服务.allLocations,所以我在 html 组件上进行更改以接受您的代码
  • 如果 imake 它为 this.locationsService.allLocations = this.locationsService.allLocations.reduce .... 是否可行。
  • 我需要按照上面的评论做,因为如果我使 var res=this.locationsService html 将无法工作

标签: javascript typescript angular7 angular-directive angular-components


【解决方案1】:

原因是,一旦你.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 一次通过会更好。

【讨论】:

    【解决方案2】:

    您可以按 Locid 过滤

    var newArr = arr.filter((x, index, self) =>
      index === self.findIndex((t) => (t.Locid === x.Locid )));
    
    console.log(newArr);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 2017-11-16
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      相关资源
      最近更新 更多