Manipulating data in a different format

Issue

I managed to create a query to get some data from the database using the following 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));
});

The data comes in the following format:

[
  { 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' }
]

My question is how to transform this data in a format, like the following:

{"Hypertensive disease": ["Pain chest", "Shortness of breath", "Dizziness", "Asthenia", "Fall", "Syncope", "Vertigo", "Sweat", "Sweating increased", "Palpitation", "Nausea", "Angina pectoris", "Pressure chest"], "Diabetes": ["Polyuria"]}

Solution

You’re trying to group and transpose the data. The best way is to use .reduce() function on the array. Here’s an example:

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; }

For the given input above, I get this response:

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

Answered By – Praveen Kumar Purushothaman

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.