NodeJS 对键相同的对象数组中的键值求和[重复]

wn9m85ua  于 2022-12-22  发布在  Node.js
关注(0)|答案(2)|浏览(180)

此问题在此处已有答案

How, from an array of objects, does one group, merge and aggregate values, each task by one or more different property-names / object-keys?(1个答案)
3天前关闭。
我一直在玩这个有点,我实现了一个工作函数与一个值,但我试图实现求和多个键的地方,一个特定的键是相同的。
例如,这是我的数据:

let data = [
    {
        name: 'John',
        value1: 1,
        value2: 2,
        value3: 3,
    },
    {
        name: 'Susan',
        value1: 1,
        value2: 2,
        value3: 3,
    },
    {
        name: 'John',
        value1: 1,
        value2: 2,
        value3: 3,
    },
    {
        name: 'Kate',
        value1: 1,
        value2: 2,
        value3: 3,
    },
    {
        name: 'Susan',
        value1: 1,
        value2: 2,
        value3: 3,
    },
];

这是经过处理后的数据:

data = [
    {
        name: 'John',
        value1: 2,
        value2: 4,
        value3: 6,
    },
    {
        name: 'Susan',
        value1: 2,
        value2: 4,
        value3: 6,
    },
    {
        name: 'Kate',
        value1: 1,
        value2: 2,
        value3: 3,
    },
]

对于单个值,函数为:

function sumValuesInArrayOfObjectsByKey(arr, key, value) {
    const map = new Map();
    for (const obj of arr) {
        const currSum = map.get(obj[key]) || 0;
        map.set(obj[key], currSum + obj[value]);
    }
    const res = Array.from(map, ([k, v]) => ({ [key]: k, [value]: v }));
    return res;
}

任何帮助或指导将不胜感激。

ljsrvy3e

ljsrvy3e1#

不要试图只指定一个键来添加其值--迭代对象上除name之外的所有键,并将它们添加到Map中的匹配值。

let data=[{name:"John",value1:1,value2:2,value3:3},{name:"Susan",value1:1,value2:2,value3:3},{name:"John",value1:1,value2:2,value3:3},{name:"Kate",value1:1,value2:2,value3:3},{name:"Susan",value1:1,value2:2,value3:3}];

function sumValuesInArrayOfObjectsByKey(arr, joiningKey) {
    const map = new Map();
    for (const { [joiningKey]: name, ...rest } of arr) {
        if (!map.has(name)) {
            map.set(name, { ...rest, [joiningKey]: name });
        } else {
            const mapObj = map.get(name);
            for (const [key, value] of Object.entries(rest)) {
                mapObj[key] = (mapObj[key] ?? 0) + value;
            }
        }
    }
    return [...map.values()];
}
console.log(sumValuesInArrayOfObjectsByKey(data, 'name'));
lnlaulya

lnlaulya2#

您可以使用Array#reduce,使用对象存储每个键的结果,并对除分组键之外的所有键求和。

let data=[{name:"John",value1:1,value2:2,value3:3},{name:"Susan",value1:1,value2:2,value3:3},{name:"John",value1:1,value2:2,value3:3},{name:"Kate",value1:1,value2:2,value3:3},{name:"Susan",value1:1,value2:2,value3:3},];
let key = 'name';
let res = Object.values(data.reduce((acc, curr)=>{
  acc[curr[key]] ??= {[key]: curr[key]};
  Object.keys(curr).filter(k => k !== key).forEach(k => 
      acc[curr[key]][k] = (acc[curr[key]][k] || 0) + curr[k]);
  return acc;
}, {}));
console.log(res);

相关问题