Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash - how to pick only one item at a time from nested json?

I have a nested weather json data:

{
    "Temp": [{
            "time": "2020-08-04T12:00:00Z",
            "value": "12"
        },

        {
            "time": "2020-08-04T13:00:00Z",
            "value": "13"
        }
    ],
    "Humidity": [{
            "time": "2020-08-04T12:00:00Z",
            "value": "70"
        },

        {
            "time": "2020-08-04T13:00:00Z",
            "value": "73"
        }
    ]
}

Now (using Lodash or any other recommendation) the challenge is to somehow group them by time, and pick only one item at a time for example:

{
    "data": [{
            "time": "2020-08-04T12:00:00Z",
            "Temprature": "12",
            "Humidity": "70"
        },
        {
            "time": "2020-08-04T13:00:00Z",
            "Temprature": "13",
            "Humidity": "73"
        }
    ]
}
like image 643
TBAWG Avatar asked Aug 04 '20 09:08

TBAWG


1 Answers

Check out Object.entries(), Array.prototype.reduce(), and for...of for more info.

// Input.
const input = {
  "temperature": [
    {"time": "2020-08-04T12:00:00Z", "value": "12"}, 
    {"time": "2020-08-04T13:00:00Z", "value": "13"}
  ],
  "humidity": [
    {"time": "2020-08-04T12:00:00Z", "value": "70"},
    {"time": "2020-08-04T13:00:00Z", "value": "73"}
  ]
}

// Zip Using Time.
const zipUsingTime = x => Object.entries(Object.entries(x).reduce((acc, [key, values], index) => {
  
  // Unpack Values.
  for (const y of values) {
    const {time, value} = y
    acc[time] = {...acc[time], [key]: value}
  }

  // ..
  return acc

}, {})).map(([time, props]) => ({time, ...props}))

// Output.
const output = {
  data: zipUsingTime(input)
}

// Proof.
console.log(output)
like image 65
Arman Charan Avatar answered Sep 29 '22 11:09

Arman Charan