简体   繁体   中英

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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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