我有一个嵌套的对象格式,其中没有分配键的值,格式如下所示:
{
"data": {
"2019": {
"January": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
}
},
"2018": {
"May": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
}
}
},
}
我需要使用键
将其转换为单个数组
response.data: [{
key: "2019"
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
year: "2019-January"
},
{
key: "2018"
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
year: "2018-May"
}
]
分配值。
答案 0 :(得分:1)
类似的东西可以解决这个问题
function render({data}) {
const entries :any[] = Object['entries'](data);
const result = entries.map(yearData => {
let key = yearData[0];
let month = Object.keys(yearData[1])[0];
let monthData = yearData[1][month];
return {
key,
...monthData,
year : `${key}-${month}`
}
})
return result;
}
已更新:
以防我们有很多个月
function render({ data }) {
const entries: any[] = Object['entries'](data);
return entries.map(([key, data]) =>
Object.keys(data).map(month => ({
key,
...data[month],
year: `${key}-${month}`
}))
).reduce((acc: any[], next: any[]) => acc.concat(next), [])
}
答案 1 :(得分:1)
如果同一年有一个月以上,则第一个答案将不起作用,如以下示例所示。该代码将处理所有月份。
forecast_custom <- function(selected_fruit) {
df_sub <- subset(df, fruit == selected_fruit)
ts_sub <- ts(df_sub$sales)
data.frame(
fruit = selected_fruit,
month = 13:24,
forecasted_sales = as.numeric(forecast(ets(ts_sub))$fitted)
)
}
> map_df(unique(df$fruit), forecast_custom)
#> fruit month forecasted_sales
#> 1 Apple 13 4781.3679
#> 2 Apple 14 4781.3330
#> 3 Apple 15 4780.8736
#> 4 Apple 16 4781.2790
#> 5 Apple 17 4781.3523