我有以下数组
0: {productid: "001", containersize: "20", ContCount: 10}
1: {productid: "002", containersize: "20", ContCount: 9}
2: {productid: "001", containersize: "40", ContCount: 4}
3: {productid: "001", containersize: "20", ContCount: 20}
4: {productid: "003", containersize: "20", ContCount: 18}
5: {productid: "001", containersize: "40", ContCount: 7}
6: {productid: "003", containersize: "40", ContCount: 25}
基于此数组,我想创建一个新数组,如下所示:
0: {productid: "001", containersize20: 30, containersize40: 11, total: 41}
1: {productid: "002", containersize20: 9, containersize40: 0, total: 9}
2: {productid: "003", containersize20: 18, containersize40: 25, total: 43}
基本上,根据产品类型和20和40的容器大小对所有容器进行计数。
我使用了以下代码:
var group_to_values = data.reduce(function (obj, item) {
obj[item.productid] = obj[item.productid] || [];
obj[item.productid].push(item.ContCount);
return obj;
}, {});
var groups = Object.keys(group_to_values).map(function (key) {
return {productid: key, ContCount: group_to_values[key]};
});
但是从这里开始,我只能继续前进。
答案 0 :(得分:2)
您处在正确的轨道上,但是可以在单个.reduce
中实现它到由productid
索引的对象中,然后可以获取该对象的值以再次将其转换为数组。不要忘记将containersize
字符串强制转换为数字,以便正确添加:
const input = [
{productid: "001", containersize: "20", ContCount: 10},
{productid: "002", containersize: "20", ContCount: 9},
{productid: "001", containersize: "40", ContCount: 4},
{productid: "001", containersize: "20", ContCount: 20},
{productid: "003", containersize: "20", ContCount: 18},
{productid: "001", containersize: "40", ContCount: 7},
{productid: "003", containersize: "40", ContCount: 25}
];
const output = Object.values(input.reduce((a, { productid, containersize, ContCount }) => {
if (!a[productid]) a[productid] = {
productid,
total: 0,
containersize20: 0,
containersize40: 0,
};
a[productid]['containersize' + containersize] += ContCount;
a[productid].total += ContCount;
return a;
}, {}));
console.log(output);
请注意,这些都不是jQuery,这只是普通的内置Javascript,通常可以实现与jQuery一样好的功能。
答案 1 :(得分:2)
这非常适合reduce
。根据您的规范遍历该结构,以构建映射到键的结果对象,然后采用values数组:
const data = [
{productid: "001", containersize: "20", ContCount: 10},
{productid: "002", containersize: "20", ContCount: 9},
{productid: "001", containersize: "40", ContCount: 4},
{productid: "001", containersize: "20", ContCount: 20},
{productid: "003", containersize: "20", ContCount: 18},
{productid: "001", containersize: "40", ContCount: 7},
{productid: "003", containersize: "40", ContCount: 25}
];
const res = Object.values(data.reduce((a, e) => {
if (!(e.productid in a)) {
a[e.productid] = {
productid: e.productid,
containersize20: 0,
containersize40: 0,
total: 0
};
}
a[e.productid].containersize20 += e.containersize === "20" ? e.ContCount : 0;
a[e.productid].containersize40 += e.containersize === "40" ? e.ContCount : 0;
a[e.productid].total += e.ContCount;
return a;
}, {}));
console.log(res);