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

101
Views
¿Cómo puedo obtener datos de una matriz de objetos con una clave coincidente y combinar los otros resultados en una matriz?

quiero el resultado a continuación

Dada una matriz

 [{ "date": "JAN", "value": 5, "weight": 3 }, { "date": "JAN", "value": 4, "weight": 23 }, { "date": "FEB", "value": 9, "weight": 1 }, { "date": "FEB", "value": 10, "weight": 30 }]

y una 'fecha' clave
transformarlo en la siguiente salida:

 [{ "date": "JAN", "value": [5, 4], "weight": [3, 23] }, { "date": "FEB", "value": [9, 10], "weight": [1, 30] }]

cualquier ayuda sera muy apreciada gracias de antemano

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

0

  • Usando Array#reduce , itere sobre la matriz mientras actualiza un Map donde la primaryKey es la key y el objeto agrupado es el value
  • En cada iteración:
    • obtener el valor de la clave principal y las propiedades restantes del objeto actual
    • Usando Object#entries , obtenga la lista de pares de las propiedades
    • Usando Map#get , obtenga el valor actual de la clave principal si existe
    • Si es así, necesitamos iterar sobre las entradas usando Array#forEach y actualizar las matrices
    • Si no, creamos el objeto inicial y agregamos un nuevo par usando Map#set
  • Finalmente, usando Map#values , puede obtener la lista de objetos agrupados

 const transform = (arr, primaryKey) => [... arr.reduce((map, e) => { const { [primaryKey]: key, ...props } = e; const currentProps = Object.entries(props); const item = map.get(key); if(item) { currentProps.forEach(([ k, v ]) => item[k] = [...(item[k] ?? []), v]); } else { const obj = currentProps.reduce((acc, [ k, v ]) => ({ ...acc, [k]: Array.isArray(v) ? [...v] : [v] }), { primaryKey: key }); map.set(key, obj); } return map; }, new Map) .values() ]; console.log( transform([ { "date": "JAN", "value": 5, "weight": 3 }, { "date": "JAN", "value": 4, "weight": 23 }, { "date": "FEB", "value": 9, "weight": 1 }, { "date": "FEB", "value": 10, "weight": 30 } ], 'date') ); console.log( transform([ { type: '200', api: [ '/counter' ] }, { type: '400', api: [ '/counter' ] }, { type: '500', api: [ '/counter', '/product' ] } ], 'type') );

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!