4 回答
TA贡献1848条经验 获得超10个赞
您可以使用javascript的reduce函数
const array = [
{ "sku": 123, "val": 10 },
{ "sku": 124, "val": 12 },
{ "sku": 123, "val": 20 }
];
const result = [];
array.reduce((res, value) => {
if (!res[value.sku]) {
res[value.sku] = { "sku": value.sku, "val": 0 };
result.push(res[value.sku])
}
res[value.sku].val += value.val;
return res;
}, {});
console.log(result)
TA贡献1887条经验 获得超5个赞
您应该按 SKU 对条目进行分组,然后将条目映射到 SKU 和减少的值(总和)。
const data = [
{ "sku": 123, "val": 10 },
{ "sku": 124, "val": 12 },
{ "sku": 123, "val": 20 }
];
const groupBy = (arr, key) => arr.reduce((acc, entry) => ({
...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]
}), {});
const sum = Object.entries(groupBy(data, 'sku'))
.map(([key, values]) =>
({
'sku': key,
'val': values.reduce((acc, { val }) => acc + val, 0)
}))
console.log(sum);
.as-console-wrapper { top: 0; max-height: 100% !important; }
这是一个更加动态的版本,允许使用具有各种聚合技术的多个减速器。
const groupBy = (arr, key) => arr.reduce((acc, entry) => ({
...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]
}), {});
const aggregate = (arr, key, reducers) =>
Object.entries(groupBy(arr, key))
.map(([k1, values]) => Object.entries(reducers)
.reduce((obj, [k2, { fn, initial }]) => ({
...obj,
[k2]: values.reduce((acc, item, index, all) =>
fn(acc, item[k2], index, all), initial || 0)
}), { [key]: k1 }))
const data = [
{ "sku": 123, "val": 10, "val2": 2 },
{ "sku": 124, "val": 12, "val2": 5 },
{ "sku": 123, "val": 20, "val2": 8 }
];
const aggregated = aggregate(data, 'sku', {
'val' : { fn: (acc, val) => acc + val, initial: 0 },
'val2' : { fn: (acc, val) => acc * val, initial: 1 }
});
console.log(aggregated);
.as-console-wrapper { top: 0; max-height: 100% !important; }
TA贡献1780条经验 获得超1个赞
跟踪对象中的总和:
const arr = [
{"sku": 123, "val": 10},
{"sku": 124, "val":12},
{"sku": 123, "val": 20}
];
const sums = {};
for (const {sku, val} of arr) {
if (!(sku in sums)) {
sums[sku] = 0;
}
sums[sku] += val;
}
const result = Object.entries(sums).map(([k, v]) => ({sku: k, val: v}));
console.log(result);
TA贡献1860条经验 获得超8个赞
用于forEach构建一个带有键sku和值进行聚合的对象。从上面的对象中
获取。Object.values
const group = (arr) => {
const res = {};
arr.forEach(({sku, val}) => {
res[sku] ? (res[sku].val += val) : res[sku] = { sku, val };
});
return Object.values(res);
};
const arr = [
{ sku: 123, val: 10 },
{ sku: 124, val: 12 },
{ sku: 123, val: 20 },
];
console.log(group(arr));
添加回答
举报