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"
}
]
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With