【发布时间】:2018-03-30 01:11:02
【问题描述】:
我遇到了一个问题,我无法在 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());
}
感谢您的帮助
【问题讨论】:
标签: javascript arrays angular typescript object