gpt4 book ai didi

javascript - 使用 Lodash groupby 和 map 转换对象数组

转载 作者:行者123 更新时间:2023-11-30 08:21:27 26 4
gpt4 key购买 nike

这就是我想做的,我想把下面的数组变成它后面的数组。谁能指出我正确的方向?

原始数据

[{
"FeatureId": 1,
"District": "ANE",
"Temperature": 206,
"RelativeHumidity": 20,
"WindSpeed": 5,
"WindGust": 15
},
{
"FeatureId": 1,
"District": "ANE",
"Temperature": 196,
"RelativeHumidity": 19,
"WindSpeed": 5,
"WindGust": 15
},
{
"FeatureId": 2,
"District": "AMO",
"Temperature": 203,
"RelativeHumidity": 54,
"WindSpeed": 9,
"WindGust": 18
},
{
"FeatureId": 2,
"District": "AMO",
"Temperature": 184,
"RelativeHumidity": 46,
"WindSpeed": 12,
"WindGust": 18
}]

我想要的数据:

[
{
"FeatureId": 1,
"District": "ANE",
"TemperatureTrend": [ 206, 196 ],
"RelativeHumidityTrend": [ 20, 19 ],
"WindSpeedTrend": [ 5, 5 ],
"WindGustTrend": [ 15, 15 ]
},
{
"FeatureId": 2,
"District": "AMO",
"TemperatureTrend": [ 203, 184 ],
"RelativeHumidityTrend": [ 54, 46 ],
"WindSpeedTrend": [ 9, 12 ],
"WindGustTrend": [ 18, 18 ]
},

]

我试过组合 groupby 和 map,但无法解决问题。我也不确定如何记录这些步骤。

最佳答案

除了其他好的答案,您还可以使用 es6 解构。

var arr = [{
"FeatureId": 1,
"District": "ANE",
"Temperature": 206,
"RelativeHumidity": 20,
"WindSpeed": 5,
"WindGust": 15
},
{
"FeatureId": 1,
"District": "ANE",
"Temperature": 196,
"RelativeHumidity": 19,
"WindSpeed": 5,
"WindGust": 15
},
{
"FeatureId": 2,
"District": "AMO",
"Temperature": 203,
"RelativeHumidity": 54,
"WindSpeed": 9,
"WindGust": 18
},
{
"FeatureId": 2,
"District": "AMO",
"Temperature": 184,
"RelativeHumidity": 46,
"WindSpeed": 12,
"WindGust": 18
}]

var temp = arr.reduce((o, d) => (
{ WindSpeed, WindGust, RelativeHumidity, Temperature, ...rest } =
({
...d
, ...{
RelativeHumidityTrend: (o[d.FeatureId] && o[d.FeatureId].RelativeHumidityTrend || []).concat(d.RelativeHumidity)
, WindSpeedTrend: (o[d.FeatureId] && o[d.FeatureId].WindSpeedTrend || []).concat(d.WindSpeed)
, WindGustTrend: (o[d.FeatureId] && o[d.FeatureId].WindGustTrend || []).concat(d.WindGust)
, TemperatureTrend: (o[d.FeatureId] && o[d.FeatureId].TemperatureTrend || []).concat(d.Temperature)
}
})
, o[d.FeatureId] = rest
, o
) , {})

var result = Object.values(temp)
console.log(result)

关于javascript - 使用 Lodash groupby 和 map 转换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52961776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com