How to re structure the array dynamic way?

Below is the array format which I have currently

There are multiple categories like this, this is one of provided for example

[
   {
      "itemId":"123",
      "itemName":"name 1",
      "category":"electric",
      "salePersonName":"person name 1"
   },
   {
      "itemId":"234",
      "itemName":"name 2",
      "category":"electric",
      "salePersonName":"person name 2"
   }{
      "itemId":"345",
      "itemName":"name 3",
      "category":"electric",
      "salePersonName":"person name 3"
   }
]

But I need to restructure it to the below format, how can I do this in a dynamic way,

[
   {
      "category":"electric",
      "items":[
         {
            "temId":"123",
            "itemName":"name 1"
         },
         {
            "itemId":"234",
            "itemName":"name 2"
         },
         {
            "itemId":"345",
            "itemName":"name 3"
         }
      ],
      "salePersons":[
         {
            "salePersonName":"person name 1"
         },
         {
            "salePersonName":"person name 2"
         },
         {
            "salePersonName":"person name 3"
         }
      ]
   }
]

Below is code, which I have tried before, but is not giving expected output

   

 

const array = [{
    "itemId": "123",
    "itemName": "name 1",
    "category": "electric",
    "salePersonName": "person name 1"
  },
  {
    "itemId": "234",
    "itemName": "name 2",
    "category": "electric",
    "salePersonName": "person name 2"
  }, {
    "itemId": "345",
    "itemName": "name 3",
    "category": "electric",
    "salePersonName": "person name 3"
  },
  {
    "itemId": "34111",
    "itemName": "name 4",
    "category": "newCategory",
    "salePersonName": "person name 5"
  }
];
let result = {};
array.forEach(function(o) {
  result[o.category] = result[o.category] || {};
  result[o.category]['items'] = [{
    "itemId": result[o.itemId],
    "itemName": result[o.itemName]
  }];
  result[o.category]['salePersons'] = [{
    "salePersonName": result[o.salePersonName]
  }];
});

console.log("result", result)

Answer

const input = [
   {
      "itemId":"123",
      "itemName":"name 1",
      "category":"electric",
      "salePersonName":"person name 1"
   },
   {
      "itemId":"234",
      "itemName":"name 2",
      "category":"electric",
      "salePersonName":"person name 2"
   },{
      "itemId":"345",
      "itemName":"name 3",
      "category":"electric",
      "salePersonName":"person name 3"
   }
]
const temp = input.reduce((acc, {itemId, itemName, category, salePersonName}) => {
  const entry = (acc[category] ??= {items: [], salePersons:[]})
  entry.items.push({ itemId, itemName });
  entry.salePersons.push({ salePersonName });
  return acc;
},{})

const result = Object.entries(temp).map(([category, data]) => ({ category, ...data }))

console.log(result);