【发布时间】:2020-09-18 14:19:11
【问题描述】:
我有这个函数可以将更多对象添加到数组中,但我面临的问题是,如果数组中存在键值,它仍然会添加该键值,但我不想添加它如果已经存在。这就是我目前所拥有的
onCheckRecipe(e) {
if (e.detail.checked === true) {
let tickedRecipe = e.detail.value;
let foundRecipeIngredients = [];
let foundRecipe;
this.loadedRecipes.filter(function (el) {
if (el._id === tickedRecipe) {
el.ingredients.map((elm) => {
foundRecipe = elm;
foundRecipeIngredients.push(foundRecipe);
});
}
});
this.groceryListUpdated = foundRecipeIngredients;
this.groceryListDefault = this.groceryListDefault.concat(
this.groceryListUpdated
);
}
}
在控制台中我收到这样的消息:
(12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "", quantity: ""}
1: {_id: "5f64ac1eb227fea1f63a5ca3", name: "avocado", quantity: "50g"}
2: {_id: "5f64ac1eb227fea1f63a5ca4", name: "lemon juice", quantity: "5g"}
3: {_id: "5f64ac1eb227fea1f63a5ca5", name: "small mozzarella pearls", quantity: "70g"}
4: {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}
5: {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}
6: {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}
7: {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}
8: {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}
9: {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}
10: {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}
11: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}
length: 12
__proto__: Array(0)
我想要做的是不添加例如:杏仁粉两次,如果它已经存在,而只是数量。我尝试了很多方法,但似乎没有任何效果。如果你们有任何想法,我将不胜感激。
【问题讨论】:
-
如果
e.detail.value是 id,它将不起作用 b/c 两个“杏仁粉”都有不同的 id -
考虑编辑上面的代码以构成一个 minimal reproducible example 适合放入像 The TypeScript Playground 这样的独立 IDE 中,其中唯一存在的问题就是您要询问的问题。
-
@Emilien 是的,你是对的。我已经按名称检查了它,但仍然没有解决我的问题...
标签: javascript arrays angular typescript object