0

So I'm trying to group a given by the value of the category key. The array looks like this. Note that category can be null.

const attributes = [
    {
        category: "foo",
        x: "1",
        y: "2"
    },
    {
        category: "foo",
        x: "3",
        y: "4"
    },
    {
        category: "bar",
        x: "23",
        y: "4"
    },
    {
        category: null,
        x: "2",
        y: "7"
    }
]

How can I group it so that the result will look like this:

const attributesByCategory = [
    {
        category: "foo",
        attributes: [
            {
                category: "foo",
                x: "1",
                y: "2"
            },
            {
                category: "foo",
                x: "3",
                y: "4"
            }
        ]
    },
    {
        category: "bar",
        attributes: [
            {
                category: "bar",
                x: "23",
                y: "4"
            }
        ]
    },
    {
        category: null,
        attributes: [
            {
                category: null,
                x: "2",
                y: "7"
            }
        ]
    }
]

What function would you use or how would you approach it?

Louie
  • 17
  • 3

0 Answers0