group an array of object by group name and children

I have an array of objects . I need to group this array by groups and children . I tried to create a new array with group names as keys and values as sorted array grouped by group, but didn’t gave me the excepted format. How can I do this?

Below is my data format :

var data1 = [{
    "Name": "Apparel",
    "categoryId": 2742,
    "categoryName": "Men",
  },
  {
    "Name": "Fragrances",
    "categoryId": 2746,
    "categoryName": "Men",
  },
  {
    "Name": "Apparel",
    "categoryId": 2742,
    "categoryName": "Women",
  },
  {
    "Name": "Fragrances",
    "categoryId": 2746,
    "categoryName": "Women",
  }
];

Expected Output is :

var data2 = [{
    "categoryName": "Men",
    "children": [{
        "Name": "Apparel",
        "categoryId": 2742
      },
      {
        "Name": "Fragrances",
        "categoryId": 2746
      }
    ]
  },
  {
    "categoryName": "Women",
    "children": [{
        "Name": "Apparel",
        "categoryId": 2742
      },
      {
        "Name": "Fragrances",
        "categoryId": 2746
      }
    ]
  }
]

I worked with this Function but the output is not as expected but am very close to the solution

function groupAndSort(array, groupField, sortField) {
  var groups = {}; // This object will end being keyed by groups, and elements will be arrays of the rows within the given array, which have been sorted by the sortField
  // Put all the rows into groups
  for (var i = 0; i < array.length; i++) {
    var row = array[i];
    var groupValue = row[groupField];
    groups[groupValue] = groups[groupValue] || [];
    groups[groupValue].push(row);
  }
  // Sort each group
  for (var groupValue in groups) {
    groups[groupValue] = groups[groupValue].sort(function(a, b) {
      return a[sortField] - b[sortField];
    });
  }
  // Return the results
  return groups;
}

groupAndSort(data1, "categoryName", "position"))

This is Output of that code :

{
  Men: [{
  categoryId: 2742,
  categoryName: "Men",
  Name: "Apparel"
}, {
  categoryId: 2746,
  categoryName: "Men",
  Name: "Fragrances"
}],
  Women: [{
  categoryId: 2742,
  categoryName: "Women",
  Name: "Apparel"
}, {
  categoryId: 2746,
  categoryName: "Women",
  Name: "Fragrances"
}]
}

I am very close to the solution I need just some help to make it as expected and thank you so much for your help

Answer

The key of your groups object is the categoryName and the value is the children array so a simple mapping:

  // Return the results
  // return groups;
  return Object.entries(groups).map(([categoryName, children]) => ({categoryName, children}));