Tengo una serie de objetos en el siguiente formato.
const Employer = [{'company': 'ABC','location': 'Phase 1','year': '2012'}, {'company': 'ABC','location': 'Phase2', 'year': '2013'}, {'company': 'XYZ','location': 'Phase3','year': '2012'}];Y la salida esperada es
{ 'ABC':{ 'company': 'ABC', data:[ {'location':'Phase1','year':2012}, {'location':'Phase2', 'year':2013}] }, 'XYZ':{ 'company': 'ABC', data:[ {'location':'Phase3','year':2012}] } }Lo que he probado es
name = 'Angular'; groupedData:any; ngOnInit(){ const Employer = [{'company': 'ABC','location': 'Phase 1','year': '2012'}, {'company': 'ABC','location': 'Phase2', 'year': '2013'}, {'company': 'XYZ','location': 'Phase3','year': '2012'}]; this.groupedData = _.mapValues(_.groupBy(Employer, 'company')) console.log(this.groupedData) } } Output: { "ABC": [ { "company": "ABC", "location": "Phase 1", "year": "2012" }, { "company": "ABC", "location": "Phase2", "year": "2013" } ], "XYZ": [ { "company": "XYZ", "location": "Phase3", "year": "2012" } ] }Aquí nuevamente necesito agrupar los datos. ¿Alguien puede ayudarme a obtener el resultado esperado?
const Employers = [{ 'company': 'ABC', 'location': 'Phase 1', 'year': '2012' }, { 'company': 'ABC', 'location': 'Phase2', 'year': '2013' }, { 'company': 'XYZ', 'location': 'Phase3', 'year': '2012' }]; const output: any = {}; for (const e of Employers) { if (output[e.company]) { output[e.company].data.push({ location: e.location, year: e.year }); } else { output[e.company] = { company: e.company, data: [{ location: e.location, year: e.year }] }; } } console.log(output);A continuación se muestra un enfoque muy básico para hacerlo.
const Employers = [{'company': 'ABC','location': 'Phase 1','year': '2012'}, {'company': 'ABC','location': 'Phase2', 'year': '2013'}, {'company': 'XYZ','location': 'Phase3','year': '2012'}]; const result = {}; Employers.forEach(employer=>{ const employerTemp = {...employer} delete employerTemp.company if(!result[employer.company]){ result[employer.company] = { company: employer.company, data: [employerTemp] } } else { result[employer.company].data.push(employerTemp) } }) console.log(result)Puedes lograr lo mismo usando reduce también
Editar: respuesta fija
const Employer = [ { company: "ABC", location: "Phase 1", year: "2012" }, { company: "ABC", location: "Phase2", year: "2013" }, { company: "XYZ", location: "Phase3", year: "2012" }, ]; const groupedData = Employer.reduce((prev, current) => { if (!prev[current.company]) { prev[current.company] = { company: current.company, data: [] }; } const currentTemp = { ...current }; delete currentTemp.company; prev[current.company].data.push(currentTemp); return prev; }, {}); console.dir(groupedData, { depth: null });