我有一个嵌套的天气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"
        }
    ]
}
现在(使用Lodash或其他任何建议)面临的挑战是以某种方式将它们按时间分组,并且一次仅选择一项,例如:
{
    "data": [{
            "time": "2020-08-04T12:00:00Z",
            "Temprature": "12",
            "Humidity": "70"
        },
        {
            "time": "2020-08-04T13:00:00Z",
            "Temprature": "13",
            "Humidity": "73"
        }
    ]
}

最佳答案

查看 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)

关于javascript - Lodash-如何一次从嵌套的json中仅选择一项?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63244273/

10-11 06:47