如何在javascript中对这个对象数组进行分组或合并? [英] How to group or merge this array of objects in javascript?

查看:86
本文介绍了如何在javascript中对这个对象数组进行分组或合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的对象数组。

I have an array of objects like below for example.

{name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}

我想将它们分组并将其中的所有值相加。例如,决赛将是这样的:

I want to group them up and adding up all the values in it. For example, the final would be like this:

{name: "Mc Donald", quantity: 8, maleCount: 1, femaleCount: 1}
{name: "KFC", quantity: 54, maleCount: 3, femaleCount: 3}

我如何在JavaScript中实现这一目标?

How can I achieve this in JavaScript?

我试图在网上找到一些解决方案,但它不是我想要的解决方案。例如,解决方案

I have tried to find some solution online but it is not the one I wanted. For example this solution

推荐答案

你可以使用数组减少:

var arr = [
    {name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
    {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
    {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
    {name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
    {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
    {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
    {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
    {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
];

var finalArr = arr.reduce((m, o) => {
    var found = m.find(p => p.name === o.name);
    if (found) {
        found.quantity += o.quantity;
        found.maleCount += o.maleCount;
        found.femaleCount += o.femaleCount;
    } else {
        m.push(o);
    }
    return m;
}, []);

console.log(finalArr);

这篇关于如何在javascript中对这个对象数组进行分组或合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆