Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object exist in an array in Angular 6

Tags:

angular

I have an array of categories: this.categories

[ { "id": 6, "name": "categories.ladies_team" }, { "id": 2, "name": "categories.junior_team" }, { "id": 7, "name": "categories.master" }, { "id": 5, "name": "categories.ladies_single" }, { "id": 1, "name": "categories.junior" }, { "id": 3, "name": "categories.men_single" }, { "id": 4, "name": "categories.men_team" } ]

Now I have a new element:

const newCategory = {
    id: category.id,
    name: category.name
};

I would like to insert it if not present.

I tried:

if (!this.categories.includes(newCategory)) {
    this.categories.push(newCategory);
  }

but it is not working...

What am I doing wrong ?

like image 473
Juliatzin Avatar asked Jun 13 '18 18:06

Juliatzin


People also ask

How do you check if an object is present in an array in angular?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.

How do you check if an object is in an array TypeScript?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

How do you check if an array of object contains a value?

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.


2 Answers

Unfortunately, includes will not work unless it is the same instance. You will need to do something like;

if (!this.categories.some((item) => item.id == newCategory.id)) {
    this.categories.push(newCategory);
}
like image 189
user184994 Avatar answered Oct 14 '22 20:10

user184994


The solution given by user184994 didn't worked for me, It was only fetching the first element. I tried like this which worked for me.

let data = this.categories.find(ob => ob.id === newCategory.id);
if(data === null){
 this.categories.push(newCategory);
}
like image 25
Anindyo Bose Avatar answered Oct 14 '22 20:10

Anindyo Bose