ES6数组推送和合并(如果值已存在)

时间:2019-06-12 15:24:45

标签: javascript arrays ecmascript-6

我正在根据食谱创建购物车。

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
        });
      });
    });

但是,如果成分名称和成分单位相同,我想合并值。有什么聪明的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用`lodash'库:

在按下后使用_.uniq(array);_.uniqBy(array);

答案 1 :(得分:1)

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

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
      });
    }
  });
});