简体   繁体   English

是否可以对这种数组进行分组? [Javascript]

[英]is it possible to group this kind array? [Javascript]

I made following Array.我做了以下数组。

I need to group items by categories.我需要按类别对项目进行分组。

Is it possible to group by category?可以按类别分组吗?

I am trying and thinking but too difficult.我正在尝试和思考,但太难了。

Should I just change Array format to make simple?我应该更改数组格式以使其简单吗?

[
    {
        id: 1,
        name: apple,
        category: {
            name: 'fruit'
        }
    },
    {
        id: 2,
        name: orange,
        category: {
            name: 'frit'
        }
    },
    {
        id: 3,
        name: cucumber,
        category: {
            name: 'vegetable'
        }       
    },
    {
        id: 4,
        name: chicken,
        category: {
            name: 'meat'
        }       
    },
]

Result I want is我想要的结果是

[
    {
        category: fruit,
        items: [
            {
                id: 1,
                name: apple,
            },
            {
                id: 2,
                name: orange,
            },
        ]
    },
    {
        category: vegetable,
        items: [
            {
                id: 3,
                name: cucumber,
            },
        ]
    },
    {
        category: meat,
        items: [
            {
                id: 4,
                name: chicken,
            },
        ]
    },
]

thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢 感谢

You need to write a method to go through you array and arrange the items by their category.您需要通过您的数组为 go 编写一个方法,并按其类别排列项目。 Something like this:像这样的东西:

function groupByCategory (array) {
    let groupedArray = [];
    for (const item of array)
        if (item.category.name) {
            if (!groupedArray[category.name]) groupedArray[category.name] = [];
            groupedArray[category.name].push(item);
    }
    return groupedArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM