typescript - 更新已经存在的数组并将新数据推送到同一个数组中
问题描述
我想将数组值推送到另一个数组中,但如果已经存在数据可用,那么在推送数据时它应该只更新现有数据。代码在打字稿中。
class itemList{
constructor(public name: string, public amount: number){}
}
function DisArr(Ar1: itemList[]){
for(let item of Ar1){
console.log(item.name + " -- " + item.amount);
}
}
var Ar1 = [new itemList('Apple',3),
new itemList('Tomato',4),
new itemList('Jam',1)];
var Ar2 = [new itemList('Orange',3),
new itemList('Tomato',8),
new itemList('Grape',20)];
console.log("Array before updating : ");
DisArr(Ar1);
Ar1.push(...Ar2);
console.log("Array before updating : ");
DisArr(Ar1);
截至目前,输出为: *Array before updates : Apple -- 3 Tomato -- 4 Jam -- 1
更新后的数组:Apple -- 3 Tomato -- 4 Jam -- 1 Orange -- 3 Tomato -- 8 Grape -- 20*
但我希望输出为:*更新前的数组:Apple -- 3 Tomato -- 4 Jam -- 1
更新后的数组:Apple -- 3 Tomato -- 12 Jam -- 1 Orange -- 3 Grape -- 20*
如何更改代码以获得所需的输出?
解决方案
我有另一种解决方案使用reduce
方法并删除 Ar2 中的重复项,concat
如下所示
let result = Ar1.reduce((acc, item) => {
let found = Ar2.find(c => c.name == item.name);
if (found != undefined) {
item.amount += found.amount;
const index = Ar2.indexOf(found);
if (index > -1) {
Ar2.splice(index, 1);
}
}
acc.push(item);
return acc;
}, []);
result = result.concat(Ar2);
在 stackbliz 演示https://stackblitz.com/edit/angular-merge-array-reduce
推荐阅读
- php - PHP DOMDocument XML
- android - 登录或注册后后按禁用
- javascript - 如何监听反应语义下拉元素的变化?
- c# - C# 在不知道 XML 文档大小的情况下声明一个二维数组
- android - 在 AlertDialog 中验证 EditText
- c++ - 为什么使用大括号初始化器时继承的构造函数不起作用?(C++)
- git - Git版本控制某些文件
- twitter-bootstrap - Bootstrap 在文本中包含连字符后将整个单词换行
- twilio - Twilio 视频 - 切换摄像头无法在 android 上运行 - NotReadableError:无法启动视频源
- c# - 读取 Excel 数据 C# 窗口应用程序时出错