gpt4 book ai didi

angular - 检查对象是否存在于 Angular 6 的数组中

转载 作者:太空狗 更新时间:2023-10-29 17:44:15 25 4
gpt4 key购买 nike

我有一个类别数组: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);
}

但它不起作用...

我做错了什么?

最佳答案

不幸的是,除非是同一个实例,否则 includes 将不起作用。您将需要做类似的事情;

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

关于angular - 检查对象是否存在于 Angular 6 的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com