Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert data from Array of Objects efficiently

I am getting an array of objects like this from my API

[
    {
        [...]
        time: "2022-01-27T18:21Z",
        attributes: {
            [...]
            temp1: 12,
            temp2: 49,
            [...],
            tempN: 23
            [...]
        },
        [...]
    },
    {
        [...]
        time: "2022-01-27T18:26Z",
        attributes: {
            [...]
            temp1: 13,
            temp2: 49,
            [...],
            tempN: 22
            [...]
        },
        [...]
    },
    [...]
]

And I need to convert these to an object like this:

{
    temp1: [
        ["2022-01-27T18:21Z", 12], ["2022-01-27T18:26Z", 13], [...]
    ],
    temp2: [
        ["2022-01-27T18:21Z", 49], ["2022-01-27T18:26Z", 49], [...]
    ],
    [...]
    tempN: [
        ["2022-01-27T18:21Z", 23], ["2022-01-27T18:26Z", 22], [...]
    ]
}

I don’t know how or even if any temp values are present in the original dataset. And it is possible that one object in the API data has for example temp5, but the next does not. The dataset has at least a couple hundred to a few thousand objects.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is an efficient way to convert the dataset?

>Solution :

I guess I’d do it like a groupBy on temps…

const data = [{
    time: "2022-01-27T18:21Z",
    attributes: {
      temp1: 12,
      temp2: 49,
      tempN: 23
    },
  },
  {
    time: "2022-01-27T18:26Z",
    attributes: {
      temp1: 13,
      temp2: 49,
      tempN: 22
    },
  },
]

const byTemps = data.reduce((acc, el) => {
  let temps = Object.keys(el.attributes).filter(key => key.startsWith('temp'));
  temps.forEach(temp => {
    if (!acc[temp]) acc[temp] = [];
    acc[temp].push([el.time, el.attributes[temp]]);
  });
  return acc;
}, {});

console.log(byTemps)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading