Home > Back-end >  Merge nested Array with same key javascript
Merge nested Array with same key javascript

Time:07-07

I have to organise the array, Getting a response array like this

let data = [
    {
        date: "2022-07-01T07:26:22",
        tips: [
            { id: 1 }
        ]
    },
    {
        date: "2022-07-01T12:05:55",
        tips: [
            { id: 1 }
        ]
    },
    {
        date: "2022-07-05T13:09:16",
        tips: [
            { id: 1 }
        ]
    },
    {
        date: "2022-07-05T13:31:07",
        tips: [
            { id: 1 }
        ]
    },
    {
        date: "2022-06-29T09:21:26",
        tips: [
            { id: 1 }
        ]
    }
]

The desired output :

let data = [
    {
        '2022-07-01': [
            {
                tips: [
                    { id: 1 }
                ]
            },
            {
                tips: [
                    { id: 1 }
                ]
            },
        ]
    },
    {
        '2022-07-05': [
            {
                tips: [
                    { id: 1 }
                ]
            },
            {
                tips: [
                    { id: 1 }
                ]
            },
        ]
    },
    {
        '2022-06-29': [
            {
                tips: [
                    { id: 1 }
                ]
            },
        ]
    }
]

I need to get data with the same key in the above array format. I have tried different ways to achieve this but have not gotten the proper result Which is the best way to get the desired output.

Thanks in advance!!!

CodePudding user response:

Here is a solution using reduce. Grouping first using reduce and after that getting the values of the object using Object.values

let data = [    {        date: "2022-07-01T07:26:22",        tips: [            { id: 1 }        ]    },    {        date: "2022-07-01T12:05:55",        tips: [            { id: 1 }        ]    },    {        date: "2022-07-05T13:09:16",        tips: [            { id: 1 }        ]    },    {        date: "2022-07-05T13:31:07",        tips: [            { id: 1 }        ]    },    {        date: "2022-06-29T09:21:26",        tips: [            { id: 1 }        ]    }]

let res = Object.values(data.reduce((acc,{date,tips})=>{
  let key = date.substring(0,10)
  acc[key] = acc[key] || {[key]:[]}
  acc[key][key].push({tips})
  return acc
},{}))

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related