简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM