javascript - Angular 检查两个数组中的匹配对象,TypeScript 最佳方法

标签 javascript arrays angular typescript object

我遇到了一个问题,并且无法在 TypeScript 中解决它。我正在使用 Angular,此代码来自服务。我有这一系列的成分:

private ingredients: Ingredient[] = [
  new Ingredient('farina', 500),
  new Ingredient('burro', 80),
  new Ingredient('uccellini', 5)
];

这是模型:export class Ingredient {constructor(public name: string, public amount: number){}}

现在我想向数组添加新成分,并使用新数组的副本发出一个事件:这有效:

newIngredients = [
  new Ingredient('mais', 100),
  new Ingredient('uccellini', 5)
];

addIngredients(newIngredients: Ingredient[]) {
  this.ingredients.push(...ingredients);
  this.ingredientsChanged.emit(this.ingredients.slice());
}

但是我想检查成分数组中是否存在新的成分对象,如果存在,则将单个对象中的旧金额值和新金额值相加,并推送更新的对象,然后返回数组的副本.

预期输出:

[
  new Ingredient('farina', 500),
  new Ingredient('burro', 80),
  new Ingredient('uccellini', 10)
  new Ingredient('mais', 100)
];

我尝试使用 Set、WeakSet、Map 等方式,但我不太了解 Typescript。这就是我陷入困境的地方:

addIngredients(newIngredients: Ingredient[]) {

  let hash = {};
  this.ingredients.forEach(function (ingr) {
    hash[ingr.name] = ingr;
  });

let result = newIngredients.filter(function (ingr) {
  if (!(ingr.name in hash)) {
    return !(ingr.name in hash);
  } else {
    // ???
  }
});

  this.ingredients.push(...result);
  this.ingredientsChanged.emit(this.ingredients.slice());
}

感谢帮助

最佳答案

假设你有两个数组

const ingredients: Ingredient[] = [
  new Ingredient('farina', 500),
  new Ingredient('burro', 80),
  new Ingredient('uccellini', 5)
];

const newIngredients = [
  new Ingredient('mais', 100),
  new Ingredient('uccellini', 5)
];

如果您想将它们组合起来,如果添加不存在的成分并组合存在的成分,

你可以做的就是合并两个数组,然后减少直到只有一个列表

const combined = ingredients
  .concat(newIngredients)
  .reduce((prev: any[], curr: any) => {
    const temp = prev.filter(a => a.name === curr.name)
    if (temp.length > 0) {
      prev.push({ ...curr, value: temp.shift().value + curr.value })
    } else {
      prev.push(curr)
    }
    return prev
  }, [])

关于javascript - Angular 检查两个数组中的匹配对象,TypeScript 最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567148/

相关文章:

java - 因未知原因而出现错误

javascript - 处理 Angular 4 生命周期 Hook

javascript - 比较两个列表并将一个列表值更新为其他 angular5

在java中从服务器端执行的javascript?

PHP数组,选择打印特定元素及其内容

javascript - 在 Knockout 中读取复杂对象的计数

javascript - 如何在不输入递归的情况下请求twitter api

angular - Angular 4/5 中的条件 ng-content

javascript - JsTestDriver 和旧版 javascript。转换还是不转换?

javascript - 抽象关系比较算法: Why evaluation order is important?