'How to convert existing JSON into different JSON Structure

I am using react with typescript I have some existing JSON data of employees with respect to their department as a key.

Here is my JSON data sample:

[
  { "department": 1,  "name": "Test", "age": 32, "contact": 242222120, "id": 1 },
  { "department": 1,  "name": "Test", "age": 18, "contact": 242222120, "id": 2 },
  { "department": 1,  "name": "Test", "age": 22, "contact": 242222120, "id": 3 },
  { "department": 2,  "name": "Test", "age": 30, "contact": 242222120, "id": 1 },
  { "department": 2,  "name": "Test", "age": 27, "contact": 242222120, "id": 2 },
  { "department": 3,  "name": "Test", "age": 25, "contact": 242222120, "id": 1 }

]

Now I want to convert it into the department as a key and its respected data nested object like:

like below

{
 1:{[
    { "name": "Test", "age": 32, "contact": 242222120, "id": 1 },
    { "name": "Test", "age": 18, "contact": 242222120, "id": 2 },
    { "name": "Test", "age": 22, "contact": 242222120, "id": 3 }
   ]},
2:{[
    { "name": "Test", "age": 30, "contact": 242222120, "id": 1 },
    { "name": "Test", "age": 27, "contact": 242222120, "id": 2 }
   ]}

}

To do like above I created a type:

type DepartmentType = {
    department: number,
    name: string,
    age: number,
    contact: number,
    id: number
  }

Below I created a key-value dictionary and initialize it as empty

let department: {[department: number]: DepartmentType} = {};
const convertJSON = () => {
    let diclength: number = Object.keys(department).length;
  rawJSONData.forEach((x: DepartmentType) => {
    if(diclength === x.department){
        department[diclength] = {
            name: x.name,
            age: x.age,
            contact: x.contact,
            id: x.id
        }
    }
  })
}

I am not getting how to match department and put same department value in that array



Solution 1:[1]

you can use the spread operator with destructuring to easily create an object without the department property and use Adrien LAMOTTES answer similar to this:

const departments = users.reduce(function (a, b) {
  let {department, ...c} = b;
  a[department] = a[department] || [];
  a[department].push(c);
  return a;
}, {});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 domi