【问题标题】:How to remove object from an array if key value already exists - typescript如果键值已经存在,如何从数组中删除对象 - 打字稿
【发布时间】: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


【解决方案1】:

首先检查项目是否存在(通过findIndex),如果存在,则运行map 并仅增加正确的索引。

如果它不存在,那么,只需 concat 新项目。

包含在示例代码下方。当然,您必须适应自己的需求,但想法就在那里。

const items = [{
  _id: "1",
  name: "avocado",
  quantity: 50
}, {
  _id: "2",
  name: "pasta",
  quantity: 60
}]

function addItems(newItem) {
  const index = items.findIndex((curItem) => curItem.name === newItem.name);
  if (index >= 0) {
    return items.map((curItem, curIndex) => {
      return index === curIndex ? {
          ...curItem,
          quantity: curItem.quantity + newItem.quantity
        } :
        curItem;
    });
  } else {
    return items.concat(newItem);
  }
}

console.log('Current items', items);

console.log('Adding a known item', addItems({
  _id: "1232",
  name: "avocado",
  quantity: 50
}));

console.log('Adding a new item', addItems({
  _id: "23232332",
  name: "meat",
  quantity: 50
}));

【讨论】:

  • 根据alex的信息,同一种成分可以有不同的_id,杏仁粉5f64ac1eb227fea1f63a5c9e-5f64ac1eb227fea1f63a5c9c就是这种情况。如果这不是 Alex 的复制粘贴错误,您的函数应按 namenot _id 过滤。
  • 而且您不需要映射项目列表,因为您知道可以直接访问它的索引items[index].quantity += newItem.quantity 并更新数量属性。我向您提交您的代码更新:)
  • 嗨!是的,过滤是按名称而不是 _id 是我的错误。感谢您的帮助!
  • 我已经更新了名称过滤。而且我通常不建议对入口参数进行突变,这就是为什么我建议 map
  • 嗨@alex,您的问题还需要帮助吗?否则,请接受它解决问题的答案
【解决方案2】:

我一直在寻找类似这样的东西

onCheckRecipe(e) {
    if (e.detail.checked === true) {
      for (let recipe of this.loadedRecipes) {
        if (recipe.name === e.detail.value) {
          recipe.ingredients.forEach((eachIngredient) => {
            let matchedIng = this.groceryList.find(function (foundIng) {
              return foundIng.name === eachIngredient.name;
            });
            if (matchedIng) {
              matchedIng.quantity =
                matchedIng.quantity + eachIngredient.quantity;
            } else {
              this.groceryList.push(eachIngredient);
            }
          });
        }
      }

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2023-03-28
    • 2021-11-30
    • 2018-11-28
    • 1970-01-01
    • 2018-08-06
    • 2011-01-18
    • 2020-07-29
    相关资源
    最近更新 更多