我需要从Typescript中的对象数组构建自定义对象。
在下面的给出示例中,如何计算Salesman_1_name在数组中的次数,为每个Salesman_1_name加上毛额,并计算每个Salesman_1_name的保修是否不为空?所以,如果我有:
[
{salesman_1_name:Brian, gross:100, warranty: Easycare},
{salesman_1_name:Brian, gross:100, warranty: Easycare},
{salesman_1_name:Brian, gross:100, warranty: null},
{salesman_1_name:Kreso, gross:100, warranty: null},
{salesman_1_name:Filip, gross:100, warranty: Easycare}
]
我需要输出:
[
Name:Brian, Count:3, Gross:300, WarrantyCount:2,
Name:Kreso, Count:1, Gross:100, WarrantyCount:0,
Name:Filip, Count:1, Gross:100, WarrantyCount:1
]
最佳答案
data.reduce((acc, cur) => {
const obj = acc.find(x => x.Name === cur.salesman_1_name);
if (obj) {
obj.Gross += cur.gross;
obj.WarrantyCount = cur.warranty !== null ? obj.WarrantyCount + 1 : obj.WarrantyCount;
} else {
acc.push({ Name: cur.salesman_1_name, Gross: cur.gross, WarrantyCount: cur.warranty !== null ? 1 : 0 });
}
return acc;
}, []);
关于javascript - 遍历对象数组并输出自定义对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39660315/