【问题标题】:show a single object if an array have multiple object with same value如果数组有多个具有相同值的对象,则显示单个对象
【发布时间】:2017-06-15 07:13:35
【问题描述】:

我正在进行 url 调用,以便它返回一个 json。当我尝试将其显示到我的 html 时,我得到了必须避免的重复值。

export class ProductListPage {
 GetProductsTags: any = [];

searchProduct() {
    var url = 'myUrl';       
    this.http.get(url).map(res => res.json()).subscribe(data => {
        var getdata=JSON.parse(data.Response); 
        console.log(getdata);  
       this.storage.set("productTags", getdata);   
    });
}

fileter() {
        this.storage.get("productTags").then((data) => {
            console.log(data);
             this.GetProductsTags = data;
        })

来自 url 的 JSON 响应

 [
        {
            id: 1,
            color: "red",
            size: 'S',

        },
        {
            id: 2,
            color: "blue",
            sizes: 'M'
        },
        {
            id: 3,
            color: "red",
            sizes: 'L'
        },
        {
            id: 4,
            color: "blue",
            sizes: 'XL'
        },
        {
            id: 5,
            color: "blue",
            sizes: 'XXL'
        }

    ];

在我的 html 中

 <button (click)="fileter()">filter</button>
 <button (click)="searchProduct()">filter</button>
 <ion-label>item</ion-label>
     <ion-item *ngFor=" let item of GetProductsTags; let i=index ">
        <ion-label>{{item.color}}</ion-label>
         <ion-checkbox color="dark"></ion-checkbox>
  </ion-item> 

所以在我看来,我将每个产品的颜色作为一个列表,就像我有 5 种产品一样,列表中的 5 种颜色为“红、蓝、红、蓝、蓝、蓝”。

我需要的只是该列表中的“红色,蓝色”,我需要一些逻辑或想法来解决这个问题。 有人可以帮我吗

【问题讨论】:

  • 使用管道从数组中删除具有重复颜色的元素。

标签: json ionic2


【解决方案1】:

您可以使用以下方法删除重复项。

public removeDuplicates(){
   for(int i=0;i<this.GetProductsTags.length;i++){
      if(!(this.colors.indexOf(this.GetProductsTags[i].color) > -1)){
         this.colors.push(this.GetProductsTags[i].color);
      }
   }
}

将颜色数组初始化为全局。然后您可以使用该数组对其进行迭代。

【讨论】:

  • 我必须或何时必须调用此函数
  • 可以调用这个函数,fileter() { this.storage.get("productTags").then((data) =&gt; { console.log(data); this.GetProductsTags = data; this.removeDuplicates(); })
  • 这个GetProductsTags是指空数组吗,我用上面的代码报错
  • 现在检查..我错过了this范围..我更正了:)
  • 这意味着 GetProductsTags 没有项目。请通过在我的方法中的 for 循环之前添加 console.log(this.GetProductsTags) 来检查它是否有项目
【解决方案2】:
var uniqueColor = [];//declaring empty array
for(var data in getdata){
    if(uniqueColor.indexOf(getdata[data]['color'])==-1)//check the array, if the current color in this iteration is already pushed into the unique queue
      uniqueColor.push(getdata[data]['color']);// push the color to the unique if not already present
}
console.log(uniqueColor);

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2020-06-20
  • 2020-06-12
  • 1970-01-01
  • 2016-01-18
  • 2021-11-11
  • 2018-05-22
相关资源
最近更新 更多