Angular 2从数组中删除重复的值 [英] Angular 2 remove duplicate values from an array

查看:325
本文介绍了Angular 2从数组中删除重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,想要删除重复项

I am having an array of objects and want to remove duplicates

就像图像中的我想要删除所有重复值并仅获取单个值,并且重复项会增加数量.

Like in the image i want to remove all duplicate values and get only single values and for the duplicates increase the quantity.

推荐答案

似乎您正在实现如何在购物车中添加商品.我假设您有一个产品类或类似名称来创建对象.

It seems like you are implementing how to add items in your cart. I assume you have a product class or similar name to create your objects.

export class Product {
  constructor(
    public name: string, public amount: number, quantity: number, productId: string){} 
}

我建议您实现另一个类,例如购物车.

I suggest you implement another class, say cart.

export class Cart {
    constructor(
        public product: Product, public quantity: number) {}
}

在您的service.ts中,

In your service.ts,

carts: Cart[];

addToCart(product: Product) {
    for (let i = 0; i < this.carts.length; i++) {
        if(this.carts[i].product.productId == product.productId) {
            this.carts[i].quantity = this.carts[i].quantity + 1;
            return;
        }// this code here to avoid duplicates and increase qty.
    }

    let cart = new Cart(product, 1);
    this.carts.push(cart);
}

您的购物车中应该有3个不同的项目,即cs(3),dota(1)和nfs(1).在我的购物车中,当您单击我的产品"组件中的产品时,每件商品仅添加到购物车1个.

You should have 3 different items in your cart, cs(3), dota(1), nfs(1). In my shopping cart, only 1 per item is added to cart, when you click on the product in my products component.

for(let i=0; i<products.length; i++){
  this.addToCart(products[i]);
}

此代码如下所示

这篇关于Angular 2从数组中删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆