在Angular 6中检查一个对象是否存在于数组中

8
我有一个类别数组: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" } ]

现在我有一个新元素:
const newCategory = {
    id: category.id,
    name: category.name
};

如果没有该项,我希望插入它。

我尝试了:

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

但是它没有起作用... 我做错了什么?

2
好的,你需要定义“不存在”,然后查找数组的some()元素是否与指示它存在的谓词匹配。 - JB Nizet
3个回答

25

很不幸,includes只有在相同实例时才能起作用。您需要执行以下操作:

if (!this.categories.some((item) => item.id == newCategory.id)) {
    this.categories.push(newCategory);
}

一些函数返回 true/false,而 find 函数返回数组中找到的项或在未找到该项时返回 undefined。因此,有时候仅仅知道数组中是否存在某个项,some 函数就非常有用了。 - Ravi Shankar Kota

5
用户user184994提供的解决方案对我无效,它只能获取第一个元素。我尝试了以下方法,这对我起作用了。
let data = this.categories.find(ob => ob.id === newCategory.id);
if(data === null){
 this.categories.push(newCategory);
}

如果未找到元素,则数据将为未定义而不是空。 - Gobind Gupta

0

Anindyo Bose的解决方案也不起作用。将null检查替换为undefined对我有用。

let data = this.categories.find(ob => ob.id === newCategory.id);
 if(data === undefined){
      this.categories.push(newCategory);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接