Grouping all JSON key based on values in Typescript

Viewed 263

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"}
                 ]
        } 
      ]
2 Answers

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);

You could try with the array reduce function. I'd also say having hobby and id properties inside the objects is redundant since the variable name already implies the meaning of the data contained within the properties.

var 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"}
];

var ID = x.reduce((acc, curr) => {
  acc[curr.id] = acc[curr.id] || [];
  acc[curr.id].push(curr.hobby);
  return acc;
}, Object.create(null));

var Hobby = x.reduce((acc, curr) => {
  acc[curr.hobby] = acc[curr.hobby] || [];
  acc[curr.hobby].push(curr.id);
  return acc;
}, Object.create(null));

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

Related