将具有相同键的对象组合成数组中的一个对象- Typescript



我有这个数组Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}]

我想得到这个Arr = [{ code: "code1", id: "14", count: 61}]

注意:我想要合并的对象中的所有字段都是相同的,除了count,这是我想要求和的字段。

你可以这样做:

// create new array that will keep your new objects:
var newArray = [];
// iterate over objects in original array:
this.originalArray.forEach((item) => {
// create new object that you *might* push into new array;
// use 'id' property of the current item in iteration:
var newItem = { id: item.id, code: null, count: 0 };
// iterate again over original array's objects to compare
// each of them with the current item from upper iteration:
this.originalArray.forEach((innerItem, i) => {
// check if they have the same id:
if (innerItem.id == item.id) {
// if they do, set values of a new object by adding 
// the count values
newItem.count = newItem.count + innerItem.count;
// and setting the code to be the same as in item from upper iteration
newItem.code = item.code;
}
});
// push new object to new array only if the new array doesn't already have
// an item with that id:
if (!newArray.some((x) => x.id == newItem.id)) newArray.push(newItem);
});
console.log(newArray);

我猜你可以有任意数量的项目具有相同的id在你的数组,所以这也适用于。

STackblitz示例:https://stackblitz.com/edit/angular-ivy-1hkspy

最新更新