Angular2比较两个数组和对象,并删除两者中存在的任何数组和对象

时间:2016-11-08 09:28:20

标签: arrays object angular

我目前正在编写一个允许用户向产品添加类别的应用程序。我将从我的API以及已分配给该产品的类别中提取所有类别。然后我想比较两个对象数组,如果该类别已经在该产品的已分配类别中,我不想将其显示为产品分配的选项,因此您无法添加产品已分配给它的类别。

以下是我的API数据示例:

产品的分配类别:

{id: "3", name: "Vitamins and Minerals ", description: "", created_at: "2016-08-15 09:21:05",…}

我的申请表上的所有类别:

0:
{id: "1", name: "Detergents and Disinfectants", description: "", created_at: "2016-08-15 09:21:05",…}
1
:
{id: "2", name: "Poultry Equipment", description: "", created_at: "2016-08-15 09:21:05",…}
2
:
{id: "3", name: "Vitamins and Minerals ", description: "", created_at: "2016-08-15 09:21:05",…}
3
:
{id: "4", name: "Gut Health ", description: "", created_at: "2016-08-15 09:21:05",…}
4
:
{id: "5", name: "Rodent, Mite and Fly Control", description: "", created_at: "2016-08-15 09:21:05",…}
5
:
{id: "6", name: "Protective Clothing", description: "", created_at: "2016-08-15 09:21:05",…}

现在,正如您所看到的,需要从我的类别中删除已分配的类别以显示数组,因此它不是该产品的选项。我似乎无法从阵列中取出它。我在视图上试过这个:

<a *ngIf='allocatedCategories.indexOf(category) === -1'>{{category.name}}<i class='glyphicon glyphicon-plus'></i></a>

但是这不起作用,而且还在控制器上:

alreadyAllocated(category) {
        for(var i = 0; i < this.allocatedCategories; i++) {
            if(this.allocatedCategories[i]['id'] == category.id) {
                return false;
            }
        }
        return true;
    }

如果它有帮助,这是我的整个组件控制器:

import { Component, Input } from "@angular/core";
import { Product } from "../../../../classes/Product";
import { ProductService } from "../../../../services/product.service";
import { Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { Location } from '@angular/common';
import { TabsService } from "../../../../services/tabs.service";
import { CategoryService } from "../../../../services/category.service";

@Component({
    selector: 'product-edit',
    templateUrl: '/app/views/catalog/products/directives/product-edit.html',
    moduleId: module.id
})

export class ProductEditComponent {
    public product:Product;
    private categories = {};
    private allocatedCategories = [];
    private searchTerm = '';
    private _subscription: Subscription;
    public id: number;
    public tabs:Array<any> = [
        {title: 'General', content: '', active: true, linked: 'general'},
        {title: 'Images', content: '', active: false, linked: 'images'},
        {title: 'Categories', content: '', active: false, linked: 'categories'},
        {title: 'Manufacturers', content: '', active: false, linked: 'manufacturers'}
    ];
    private selectedTab: Object = this.tabs[0];

        constructor(
        private _productService: ProductService,
        private _categoryService: CategoryService,
        private _activatedRoute: ActivatedRoute,
        private _location: Location,
        private _tabsService: TabsService
    ) {
        this._tabsService.emitter
            .subscribe((tab) => {
                this.tabs.filter((arrayItem) => {
                    if(arrayItem.title === tab.title) {
                        this.selectedTab = arrayItem;
                    }
                });
            }, () => {

            }, () => {

            });

    }

    getProduct() {
        var self = this;
        this._productService.getProduct(this.id)
            .subscribe(
                (product) => {
                    self.product = product[0];
                }
            );
    }

    getCategories(filters) {
        var self = this;
        this._categoryService.getCategories(filters)
            .subscribe((categories) => {
                self.categories = categories;
            });

    }

    getAllocatedCategories() {
        var self = this;
        this._categoryService.getCategories({
            product: self.id
        }).subscribe((categories) => {
            self.allocatedCategories = categories;
        });
    }

    searchCategories() {
        var self = this;
        this.getCategories({
            'search_term' : self.searchTerm
        });
    }

    alreadyAllocated(category) {
        for(var i = 0; i < this.allocatedCategories; i++) {
            if(this.allocatedCategories[i]['id'] == category.id) {
                return false;
            }
        }
        return true;
    }

    back() {
        this._location.back();
    }

    ngOnInit() {
        var self = this;
        this._subscription = this._activatedRoute.params.subscribe(params => {
            self.id = +params['id'];
            this.getProduct();
        });
        this.getCategories({});
        this.getAllocatedCategories();
    }

    ngOnDestroy() {
        this._subscription.unsubscribe();
    }
}

有人能看出为什么这不起作用吗?

由于

1 个答案:

答案 0 :(得分:1)

如何使用方法从数组中删除重复的类别?

private removeDuplicatedCategories(prodCategories: any[], toBeRemoved: any[]) {
    let i: number = 0;
    while (i < prodCategories.length) {
        for (let toRem of toBeRemoved) {
            if (toRem.id === prodCategories[i].id) {
                prodCategories.splice(i, 1); // remove duplicated
                continue;
            }
        }
        ++i;
    }
}

上述方法将修改原始数组。相反,如果要保留原始类别数组,可以让此方法返回另一个包含非重复类别的数组:

private removeDuplicatedCategories(prodCategories: any[], toBeRemoved: any[]): any[] {
    let ret: any[] = []; // new array to be returned
    for (let pc of prodCategories) {
        let isDup: boolean = false;
        for (let toRem of toBeRemoved) {
            if (pc.id === toRem.id) {
                isDup = true;
                break;
            }
        }
        if (!isDup) ret.push(pc); // append non-duplicated
    }
    return ret;
}