0

This question is the extention of this question. which is here Underscore js group by each month on each year This is giving the expected result and the code which i am using is here.

   const months = [
        'jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'
    ]
    const result = flashMessage.reduce((res:any, item:any) => {
        const date = new Date(item.created_at)
        const year = date.getFullYear();
        const month = months[date.getMonth()];
        const existingYear = res[year] || {}
        res[year] = existingYear
        const updated  = [...(existingYear[month] || []), item]
        res[year][month] = updated
        return res
     }, {});

This is the answer which it is producing now.

{
  "2022": {
    "jan": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 2,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 1,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
    ]
  }
}

What if i want the result in a single level.

{
  "2022 jan": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
      {
        "id": 2,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 1,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
    ]
  "2022 feb": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-02-31T07:00:01.880Z"
      }
    ]
  "2021 feb": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2021-02-31T07:00:01.880Z"
      }
    ]
}

Is there any way i can do this?

xxoyx
  • 81
  • 8
  • Does this answer your question? [Fastest way to flatten / un-flatten nested JSON objects](https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects) – Dhana D. Feb 02 '22 at 07:39
  • `existing=res[\`${year} ${mon}\`] ||[]; res[\`${year} ${mon}\`] = [...existing, item]` – derpirscher Feb 02 '22 at 07:40
  • Can you post it as answer so that i can accept the same. – xxoyx Feb 02 '22 at 09:44

0 Answers0