Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Agrupar una matriz de objetos en un objeto de matrices por múltiples claves y agregar las identificaciones del grupo a la clave

Ejemplo hecho de código -

Interfaz -

 interface IInterface { id: number; name: string; age: number; }

matriz -

 const arr: IInterface[] = [ { id: 1, name: 'daniel', age: 12 }, { id: 2, name: 'jonny', age: 13 }, { id: 3, name: 'daniel', age: 12 }, { id: 4, name: 'daniel', age: 12 } ]

Función agrupar por -

 const GroupBy = ( array: IInterface[], f: (element: IInterface) => (string | number | undefined)[] ) => { const groups: { [key: string]: IInterface[] } = {}; array.forEach((object) => { const group = f(object).join("-"); groups[group] = groups[group] || []; groups[group].push(object); }); return groups; };

Usando la función groupBy -

 const Grouped = GroupBy(arr, (element: IInterface) => { return [ element.name, element.age, ]; });

Resultado ahora -

 { "daniel-12": [ { "id": 1, "name": "daniel", "age": 12 }, { "id": 3, "name": "daniel", "age": 12 }, { "id": 4, "name": "daniel", "age": 12 } ], "jonny-13": [ { "id": 2, "name": "jonny", "age": 13 } ] }

resultado buscado -

 { "daniel-12-ids-1-3-4": [ { "id": 1, "name": "daniel", "age": 12 }, { "id": 3, "name": "daniel", "age": 12 }, { "id": 4, "name": "daniel", "age": 12 } ], "jonny-13-ids-2": [ { "id": 2, "name": "jonny", "age": 13 } ] }

Necesito que todas las identificaciones de grupo estén en el nombre de la clave ...................................... .................................................... .................................................... .............

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Podrías crear un nuevo objeto a partir del anterior.

 const grouped = { "daniel-12": [{ id: 1, name: "daniel", age: 12 }, { id: 3, name: "daniel", age: 12 }, { id: 4, name: "daniel", age: 12 }], "jonny-13": [{ id: 2, name: "jonny", age: 13 }] }, result = Object.fromEntries(Object.entries(grouped).map(([k, v]) => [ [k, 'ids', v.map(({ id }) => id).join('-')].join('-'), v ])); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!