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

151
Views
Manipulación de datos en un formato diferente

Logré crear una consulta para obtener algunos datos de la base de datos usando el siguiente script:

 app.get("/diseases", async (req, res) => { const rows = await process.postgresql.query( "SELECT ds.disease, ds.symptom FROM diseases ds" ); console.log(rows); res.status(200).send(JSON.stringify(rows)); });

Los datos vienen en el siguiente formato:

 [ { disease: ' boală hipertensivă', symptom: ' durere toracică' }, { disease: ' boală hipertensivă', symptom: ' respirație întretăiată' }, { disease: ' boală hipertensivă', symptom: ' amețeală' }, { disease: ' boală hipertensivă', symptom: ' astenie' }, { disease: ' boală hipertensivă', symptom: ' toamnă (Fall)' }, { disease: ' boală hipertensivă', symptom: ' sincopă' }, { disease: ' diabet', symptom: ' poliurie' } ]

Mi pregunta es cómo transformar estos datos en un formato, como el siguiente:

 {"Hypertensive disease": ["Pain chest", "Shortness of breath", "Dizziness", "Asthenia", "Fall", "Syncope", "Vertigo", "Sweat", "Sweating increased", "Palpitation", "Nausea", "Angina pectoris", "Pressure chest"], "Diabetes": ["Polyuria"]}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Está intentando agrupar y transponer los datos. La mejor manera es usar la función .reduce() en la matriz. Aquí hay un ejemplo:

 const arr = [ { disease: "boală hipertensivă", symptom: " durere toracică" }, { disease: "boală hipertensivă", symptom: " respirație întretăiată" }, { disease: "boală hipertensivă", symptom: " amețeală" }, { disease: "boală hipertensivă", symptom: " astenie" }, { disease: "boală hipertensivă", symptom: " toamnă (Fall)" }, { disease: "boală hipertensivă", symptom: " sincopă" }, { disease: "diabet", symptom: " poliurie" } ]; console.log(arr.reduce((group, row) => { // Check if disease group has the disease if (typeof group[row.disease] === "undefined") { // Initialise an array. group[row.disease] = []; } // Push the symptoms. group[row.disease].push(row.symptom.trim()); // return the updated group. return group; }, {}));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Para la entrada dada arriba, obtengo esta respuesta:

 { "boală hipertensivă": [ "durere toracică", "respirație întretăiată", "amețeală", "astenie", "toamnă (Fall)", "sincopă" ], "diabet": [ "poliurie" ] }
about 4 years ago · Juan Pablo Isaza Report

0

return rows.reduce((acc, item) => { if (!!acc[item.disease]) acc[item.disease].push(item.symptom); else acc[item.disease] = [item.symptom]; return acc; }, {})

La función de reduce toma dos parámetros: una función de procesamiento de iteración, que acumula un resultado, y un resultado inicial (ponemos como resultado inicial un objeto vacío {} ).

El procesador de iteración tiene dos parámetros: el objeto acumulador acc y el item actual, y debe devolver un objeto acumulador nuevo (o modificado).

En cada iteración, nuestra función verifica si acc ya tiene un campo con el valor de 'enfermedad'. Si no es así, crea este campo y coloca 1 matriz de elementos [item.symptom] dentro. Si el campo ya existe, envía un síntoma a esa matriz. Después de procesar los datos, obtenemos el objeto con enfermedades como claves y matrices de sus síntomas como valores.

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!