Search code examples
javascriptjsonangulartypescriptmapreduce

Grouping all JSON key based on values in Typescript


I want to create Two JSON from a single JSON based on the values. Consider below is the main JSON structure.

x = [
{id:"1",hobby:"videogames"},
{id:"1",hobby:"chess"},
{id:"2",hobby:"chess"},
{id:"3",hobby:"carrom"},
{id:"4",hobby:"videogames"},
{id:"4","hobby:"carrom"}
]

I want to create two JSON's based on the ID and Hobby. Such that each unique ID will have a array with its respective hobby and also each unique hobby will have an array with its respective provider

ID =[
    { 
      1: [
          {hobby:"videogames"},
          {hobby:"chess"}
         ]
    },
    {
     2: [
         {hobby:"chess"}
        ]
    },
    {
     3: [
         {hobby:"carrom"}
        ]
    },
    {
     4: [
         {hobby:"videogames"},
         {hobby:"carrom"}
       ]
    }        
    ];

Hobby= [
        {
          videogames:[
                      {id:"1"},
                      {id:"4"}
                     ]
        },
        {
          chess:[
                 {id:"2"}
                ]
        },
        {
          carrom:[
                  {id:"3"},
                  {id:"4"}
                 ]
        } 
      ]

Solution

  • You need to apply array.reduce function to build a dictionary wher ids or hobbies are keys and then run array.map to transform such dictionary into multiple array entries:

    let x = [
       {id:"1",hobby:"videogames"},
       {id:"1",hobby:"chess"},
       {id:"2",hobby:"chess"},
       {id:"3",hobby:"carrom"},
       {id:"4",hobby:"videogames"},
       {id:"4",hobby:"carrom"}
    ];
    
    let grouped = x.reduce((acc, cur) => {
      let {id, ...rest} = cur;
      if(!acc[id]){
         acc[id] = [];
      }
      acc[id].push(rest);
      return acc;
    }, {});
    
    let result = Object.entries(grouped).map(([key, value]) => ({[key]: value}))
    
    console.log(result);