我有一个动态数组,我需要对其求和。
{ClientName: "A", Alex: 2, Da: 0, Cal: 0}
{ClientName: "b", Alex: 0, Da: 0, Cal: 4}
{ClientName: "c", Alex: 1, Da: 0, Cal: 5}
{ClientName: "d", Alex: 2, Da: 0, Cal: 0}
在此数组中,客户端名称是固定的,但其他列(例如Alex,Da,Cal)是动态的,并且会有所不同。我需要在打字稿中创建一个通用函数,其输出将是这样的。
{ClientName: "Total", Alex: 5, Da: 0, Cal: 9}
答案 0 :(得分:3)
您可以尝试以下操作:
想法:
Object.keys
获取所有可枚举的密钥。ClientName
的硬编码值,因此可以循环设置或循环设置。
const data = [
{ClientName: "A", Alex: 2, Da: 0, Cal: 0},
{ClientName: "b", Alex: 0, Da: 0, Cal: 4},
{ClientName: "c", Alex: 1, Da: 0, Cal: 5},
{ClientName: "d", Alex: 2, Da: 0, Cal: 0},
]
const output = data.reduce((acc, item) => {
Object
.keys(item)
.forEach((key) => {
acc[key] = (acc[key] || 0) + item[key]
});
acc.ClientName = 'Total'
return acc;
}, {})
console.log(output)
答案 1 :(得分:2)
您可以减少所需的值。
var data = [{ ClientName: "A", Alex: 2, Da: 0, Cal: 0 }, { ClientName: "b", Alex: 0, Da: 0, Cal: 4 }, { ClientName: "c", Alex: 1, Da: 0, Cal: 5 }, { ClientName: "d", Alex: 2, Da: 0, Cal: 0 }],
total = data.reduce((a, { ClientName, ...b }) => Object.assign(
{},
a,
{ ClientName: 'total' },
...Object.entries(b).map(([k, v]) => ({ [k]: (a[k] || 0) + v }))
));
console.log(total);
答案 2 :(得分:0)
只要将ClientName之外的所有键都定义为数字,沿这行的内容就应该起作用
arr.reduce((sumObject, item) => {
Object.keys(item).forEach(key => {
if(key === 'ClientName'){
return false
}
if(!sumObject[key]) {
sumObject[key] = item[key]
} else {
sumObject[key] += item[key]
}
})
return sumObject
}, {ClientName: 'Total'})
答案 3 :(得分:0)
您可以使用reduce
进行迭代以生成单个输出并合并键计数,您可以使用Object.keys
和map
来迭代对象键。还添加了一个动态密钥Abc: 9
只是为了验证结果。
const object = [{
ClientName: "A",
Alex: 2,
Da: 0,
Cal: 0
},
{
ClientName: "b",
Alex: 0,
Da: 0,
Cal: 4
},
{
ClientName: "c",
Alex: 1,
Da: 0,
Cal: 5
},
{
ClientName: "d",
Alex: 2,
Da: 0,
Cal: 0,
Abc: 9
},
]
const result = object.reduce((accumulator, currentValue) => {
Object.keys(currentValue).map((indexKey) => {
accumulator[indexKey] = (accumulator[indexKey] || 0) + currentValue[indexKey]
});
accumulator.ClientName = "Total";
return accumulator;
})
console.log(result);
答案 4 :(得分:-1)
FROM node:10-alpine AS build
WORKDIR /app
COPY client/ ./
ET cetera
选中此项可以简单地得到答案