Search code examples
javascriptarraysdata-structuresjavascript-objects

Group Javascript objects in array with same key and adding new array


I am trying to change the data structure of an array of objects in JS. I have an array of objects that contain the same keys that I would like to merge to one for example route. And then would like to add query and time in a new array. Example below:

How do I change this data structure:

const array = [
    {
        query: "query1",
        route: "home",
        time: 1234
    },
    {
        query: "query2",
        route: "dashboard",
        time: 4324
    },
    {
        query: "query3",
        route: "home",
        time: 1200
    },
    {
        query: "query4",
        route: "admin",
        time: 3333
    },
    {
        query: "query5",
        route: "admin",
        time: 5435
    },
]

to become this:

const array = [
                {
                    route: "home",
                    calls: [
                        {
                            query: "query1",
                            time: 1234
                        },
                        {
                            query: "query3",
                            time: 1200
                        },
                    ]
                },
                {
                    route: "dashboard",
                    calls: [
                        {
                            query: "query2",
                            time: 4324
                        },
                    ]
                },
                {
                    route: "admin",
                    calls: [
                        {
                            query: "query4",
                            time: 3333
                        },
                        {
                            query: "query5",
                            time: 5435
                        },
                    ]
                }
            ]

Thanks in advance


Solution

  • You can use reduce method and group the array with key equal to route property, and then use Object.values to get the values of the object.

    const array = [
        {
            query: "query1",
            route: "home",
            time: 1234
        },
        {
            query: "query2",
            route: "dashboard",
            time: 4324
        },
        {
            query: "query3",
            route: "home",
            time: 1200
        },
        {
            query: "query4",
            route: "admin",
            time: 3333
        },
        {
            query: "query5",
            route: "admin",
            time: 5435
        },
    ]
    
    const result = Object.values(array.reduce((acc, item) => {
      acc[item.route] ? acc[item.route].cells.push({query: item.query, time: item.time}) : (acc[item.route] = {route: item.route, cells: [{query: item.query, time: item.time}]})
      return acc
    }, {}))
    
    console.log(result)