Lodash - 如何一次只从嵌套的 json 中选择一项?

TBA*_*AWG 7 javascript json object lodash reactjs

我有一个嵌套的天气 json 数据:

{
    "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"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在(使用 Lodash 或任何其他推荐)面临的挑战是以某种方式按时间对它们进行分组,并且一次只选择一个项目,例如:

{
    "data": [{
            "time": "2020-08-04T12:00:00Z",
            "Temprature": "12",
            "Humidity": "70"
        },
        {
            "time": "2020-08-04T13:00:00Z",
            "Temprature": "13",
            "Humidity": "73"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Arm*_*ran 1

查看Object.entries()Array.prototype.reduce()for...of了解更多信息。

// 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)
Run Code Online (Sandbox Code Playgroud)