如果数组具有多个具有相同值的对象

时间:2017-06-15 07:13:35

标签: json ionic2

我正在进行网址调用,以便返回一个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;
        })

来自网址的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种颜色&#34;红色,蓝色,红色,蓝色,蓝色,蓝色&#34;

我需要的只是&#34;红色,蓝色&#34;在该列表中,我需要一些逻辑或想法来解决这个问题。 有人可以帮助我

2 个答案:

答案 0 :(得分:0)

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

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);
      }
   }
}

将colors数组初始化为全局。然后你可以使用那个数组来迭代它。

答案 1 :(得分:0)

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);
相关问题