Search code examples
javascriptjsontransformation

JSON groupBy javascript, returning multiple fields in the parent object


I'm trying to figure out how to run a groupBy on a JSON file that has a unique identifier for the field I want to group on, then returns that grouped info as a new object while also retaining some fields from the original json object

Starting with this:

[{
  StoreId: 1,
  StoreName: "Adventure Works"
  StoreCity: "New York",
  FirstName: "John",
  LastName: "Smith",
  EmployeeId: 1,
  EmployeeAge: 25
  },
  {
  StoreId: 1,
  StoreName: "Adventure Works"
  StoreCity: "New York",
  FirstName: "Jane",
  LastName: "Doe",
  EmployeeId: 2,
  EmployeeAge: 30
  },
  {
  StoreId: 2,
  StoreName: "Amazon"
  StoreCity: "Seattle",
  FirstName: "Jeff",
  LastName: "Bezos",
  EmployeeId: 1,
  EmployeeAge: 30
}]

I want to figure out how to return this:

[{
  StoreId: 1,
  StoreName: "Adventure Works"
  StoreCity: "New York",
  Employees: [{
              FirstName: "John",
              LastName: "Smith",
              EmployeeId: 1,
              EmployeeAge: 25
              },
              {
              FirstName: "Jane",
              LastName: "Doe",
              EmployeeId: 2,
              EmployeeAge: 30
              }]
   },
   {
   StoreId: 2,
   StoreName: "Amazon"
   StoreCity: "Seattle",
   Employees: [{
                FirstName: "Jeff",
                LastName: "Bezos",
                EmployeeId: 1,
                EmployeeAge: 30
               }]
}]

Solution

  • this should be your answer...

    const truc = 
      [ { StoreId: 1, StoreName: 'Adventure Works', StoreCity: 'New York', FirstName: 'John', LastName: 'Smith', EmployeeId: 1, EmployeeAge: 25 } 
      , { StoreId: 1, StoreName: 'Adventure Works', StoreCity: 'New York', FirstName: 'Jane', LastName: 'Doe',   EmployeeId: 2, EmployeeAge: 30 } 
      , { StoreId: 2, StoreName: 'Amazon',          StoreCity: 'Seattle',  FirstName: 'Jeff', LastName: 'Bezos', EmployeeId: 1, EmployeeAge: 30 } 
      ] 
    
    const group = truc.reduce((a,c,i)=>
      {
      let {StoreId,StoreName,StoreCity,FirstName,LastName,EmployeeId,EmployeeAge} = c
      if (a.key!== StoreId)
        {
        a.key = StoreId
        a.idx = a.res.push( {StoreId, StoreName, StoreCity, Employees: [] }) -1
        }
      a.res[a.idx].Employees.push( {FirstName, LastName, EmployeeId, EmployeeAge}) 
      return (i===a.max) ? a.res : a
      }
      ,{key:null, idx:null, max:truc.length -1, res:[]}
      )
    
    console.log( JSON.stringify(group,0,2) )
    .as-console-wrapper { max-height: 100% !important; }