簡體   English   中英

是否可以對這種數組進行分組? [Javascript]

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

我做了以下數組。

我需要按類別對項目進行分組。

可以按類別分組嗎?

我正在嘗試和思考,但太難了。

我應該更改數組格式以使其簡單嗎?

[
    {
        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'
        }       
    },
]

我想要的結果是

[
    {
        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,
            },
        ]
    },
]

感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝 感謝

您需要通過您的數組為 go 編寫一個方法,並按其類別排列項目。 像這樣的東西:

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