首页 > 解决方案 > 按 1 个键对对象数组进行分组,并拆分 1 个属性

问题描述

我有这个对象数组

test = [
    {
        'id': 1,
        'name': 'XYZ'
        'value': 10
        'quantity': 100
    }, 
    {
        'id': 1,
        'name': 'XYZ'
        'value': 20
        'quantity': 200
    }, 
    {
        'id': 2,
        'name': 'ABC'
        'value': 11
        'quantity': 111
    }, 
    {
        'id': 2,
        'name': 'ABC'
        'value': 22
        'quantity': 222
    }
]

我想按 id 对它们进行分组,但名称和 {value, quantity} 分开,如下所示:

result = {
    1: [
        'name': 'XYZ'
        'items': [
            {
                'value': 10
                'quantity': 100
            },
            {
                'value': 20
                'quantity': 200
            }
        ]
    ], 
    2: [
        'name': 'ABC'
        'items': [
            {
                'value': 11
                'quantity': 111
            },
            {
                'value': 22
                'quantity': 222
            }
        ]
    ], 
}

知道我该怎么做吗?我可以按 id 分组,但我无法提取名称。谢谢

标签: javascriptarraysjsongroup-by

解决方案


我认为您可以reduce()在这种情况下使用将元素分组id

const test = [
    {
        'id': 1,
        'name': 'XYZ',
        'value': 10,
        'quantity': 100,
    }, 
    {
        'id': 1,
        'name': 'XYZ',
        'value': 20,
        'quantity': 200,
    }, 
    {
        'id': 2,
        'name': 'ABC',
        'value': 11,
        'quantity': 111,
    }, 
    {
        'id': 2,
        'name': 'ABC',
        'value': 22,
        'quantity': 222,
    }
];

const res = test.reduce((ac, {id, name, ...rest}) => ({...ac, [id]: ac[id] ? [...ac[id], rest] : [rest] }), {});
console.log(res)


推荐阅读