javascript JS按属性分组对象

nmpmafwu  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(142)

我有一个这样的数组:

[
{groupId:4,group:"g4",name:"Luke",value:12},
{groupId:3,group:"g3",name:"Mike",value:21},
{groupId:3,group:"g3",name:"Greg",value:33},
{groupId:4,group:"g4",name:"Harry",value:42},
{groupId:4,group:"g4",name:"David",value:13},
{groupId:4,group:"g4",name:"John",value:14},
{groupId:3,group:"g3",name:"Joe",value:23},
{groupId:2,group:"g2",name:"Albert",value:32},
{groupId:2,group:"g2",name:"Marie",value:25}
]

我想按组名对它进行分组,首先在屏幕上写出组(顺序无关紧要)和ID,然后是属于该组的组名下的所有名称/值对。之后,所有其他组也是如此...所以我的屏幕看起来像这样:

g4:4
Luke:12
Harry:42
David:13
John:14
g3:3
Mike:21
Greg:33
Joe:23
g2:2
Albert:32
Marie:25

我如何才能做到这一点?

dxxyhpgq

dxxyhpgq1#

我想你需要这样的东西

function printGrouped(objArray) {
    let out = {};
    for (var i = 0; i < objArray.length; i++) {
        let obj = objArray[i]
        if (!out.hasOwnProperty(obj.group)) {
            out[obj.group] = [];
        }
        out[obj.group].push(obj);
    }
    for (group in out) {
        console.log(group);
        out[group].forEach(function(obj) {
            console.log(obj.name + ":" + obj.value);
        });
    }
}
bbuxkriu

bbuxkriu2#

单一循环和Array.reduce方法

const objArray = [
    { groupId: 4, group: "g4", name: "Luke", value: 12 },
    { groupId: 3, group: "g3", name: "Mike", value: 21 },
    { groupId: 3, group: "g3", name: "Greg", value: 33 },
    { groupId: 4, group: "g4", name: "Harry", value: 42 },
    { groupId: 4, group: "g4", name: "David", value: 13 },
    { groupId: 4, group: "g4", name: "John", value: 14 },
    { groupId: 3, group: "g3", name: "Joe", value: 23 },
    { groupId: 2, group: "g2", name: "Albert", value: 32 },
    { groupId: 2, group: "g2", name: "Marie", value: 25 },
];

function sortBygroup(a, b) {
    if (a.group > b.group) return -1;
    else if (a.group < b.group) return 1;

    return 0;
}
objArray.sort(sortBygroup);

const output = objArray.reduce((acc, crt) => {
    if (!acc[crt.group]) {
        acc[crt.group] = {};
        console.log(crt.group);
    }
    console.log(crt.name + ":" + crt.value);
    return acc;
}, {});

相关问题