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 ?
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.
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 .
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With