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

179
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

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!