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

133
Views
¿Alguien puede sugerir una forma de agrupar una matriz de objetos por una clave de objeto y luego crear una nueva matriz de objetos basada en la agrupación en JavaScript?

Por ejemplo, tengo una matriz como esta. Aquí hay objetos de matriz para la misma fecha y diferentes valores.

 [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "2020-12-31T18:30:00.000Z", "value2": 362 }, { "date": "2020-12-31T18:30:00.000Z", "value3": 699 }, { "date": "2021-03-01T18:30:00.000Z", "value": 269 }, { "date": "2021-03-01T18:30:00.000Z", "value2": 450 }, { "date": "2021-03-02T18:30:00.000Z", "value3": 841 }, { "date": "2021-04-03T18:30:00.000Z", "value": 700 }, ]

Quiero hacer una matriz agrupada y fusionada para la fecha como se muestra a continuación. Los diferentes valores con la misma "fecha" se fusionan en un objeto de matriz.

 [ { "date": "2020-12-31T18:30:00.000Z", "value": 450, "value2": 362, "value3": 699 }, { "date": "2021-03-01T18:30:00.000Z", "value": 269, "value2": 450 }, { "date": "2021-03-02T18:30:00.000Z", "value3": 841 }, { "date": "2021-04-03T18:30:00.000Z", "value": 700 } ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede lograr el resultado de manera eficiente usando Map y reducir

 const arr = [ { date: "2020-12-31T18:30:00.000Z", value: 450, }, { date: "2020-12-31T18:30:00.000Z", value2: 362, }, { date: "2020-12-31T18:30:00.000Z", value3: 699, }, { date: "2021-03-01T18:30:00.000Z", value: 269, }, { date: "2021-03-01T18:30:00.000Z", value2: 450, }, { date: "2021-03-02T18:30:00.000Z", value3: 841, }, { date: "2021-04-03T18:30:00.000Z", value: 700, }, ]; const dict = arr.reduce((acc, curr) => { const { date, ...rest } = curr; if (!acc.has(date)) { acc.set(date, curr); } else { const o = acc.get(curr.date); Object.entries(curr).forEach(([k, v]) => (o[k] = v)); } return acc; }, new Map()); const result = [...dict.values()]; console.log(result);
 /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .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!