JSON组通过JavaScript,在父对象中返回多个字段

问题描述 投票:0回答:1

[我试图弄清楚如何对具有要分组字段的唯一标识符的JSON文件运行groupBy,然后将该分组信息作为新对象返回,同时还保留原始json中的某些字段对象

从此开始:

[{
  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
}]

我想弄清楚如何返回此值:

[{
  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
               }]
}]
javascript json transformation
1个回答
0
投票

这应该是你的答案...

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)=>
  {
  if (a.key!== c.StoreId)
    {
    a.key = c.StoreId
    a.siz = a.res.push( {StoreId:c.StoreId, StoreName:c.StoreName, StoreCity:c.StoreCity, Employees: [] }) -1
    }
  a.res[a.siz].Employees.push( {FirstName:c.FirstName, LastName:c.LastName, EmployeeId:c.EmployeeId, EmployeeAge:c.EmployeeAge }) 
  return (i===a.max) ? a.res : a
  }
  ,{key:null, siz:null, max:truc.length -1, res:[]}
  )

console.log( JSON.stringify(group,0,2) )
.as-console-wrapper { max-height: 100% !important; }
© www.soinside.com 2019 - 2024. All rights reserved.