Skip to content
Advertisement

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.

What is an efficient way to convert the dataset?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement