首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果值已存在,则ES6数组推送与合并

如果值已存在,则ES6数组推送与合并
EN

Stack Overflow用户
提问于 2019-06-12 23:24:46
回答 2查看 207关注 0票数 0

我正在创建一个基于食谱的购物车。

代码语言:javascript
复制
this.shoppingCartRecipes.forEach(recipe => {
      recipe.ingredients.forEach(ingredient => {
        this.shoppingCart.push({
          amount: ingredient.amount,
          unit: ingredient.unit,
          name: ingredient.ingredient,
          isDone: ingredient.isDone || false,
          recipeID: recipe.id
        });
      });
    });

但是,如果配料名称和配料单位相同,我希望合并这些值。有没有一种聪明的方法可以做到这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-12 23:40:36

如果将this.shoppingCart保留为数组:

代码语言:javascript
复制
this.shoppingCartRecipes.forEach(recipe => {
  recipe.ingredients.forEach(ingredient => {
    const shoppingCartIngredient = this.shoppingCart.find( item => (
      (item.name === ingredient.ingredient) && (item.unit === ingredient.unit)
    ))

    // If the ingredient exists, just update it
    if (shoppingCartIngredient) {
      shoppingCartIngredient.amount = ingredient.amount;
      shoppingCartIngredient.isDone = ingredient.isDone || false;
      shoppingCartIngredient.recipeID = recipe.id;
    } else {
      // Otherwise create a new record
      this.shoppingCart.push({
        amount: ingredient.amount,
        unit: ingredient.unit,
        name: ingredient.ingredient,
        isDone: ingredient.isDone || false,
        recipeID: recipe.id
      });
    }
  });
});
票数 1
EN

Stack Overflow用户

发布于 2019-06-12 23:30:52

您可以使用` `lodash‘库:

推流后使用_.uniq(array);_.uniqBy(array);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56565657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档