前言
原本是想根据后台返回数据渲染表格,但发现结构不允许。如下:
var res={
"data": {
"statistic": [
{
"time_begin": "2020-09-04",
"time_end": "2020-09-11",
"department": "营销",
"dinnerStatistic": [
{
"dinner_id": 233,
"dinner": "下午茶",
"order_count": "2",
"order_money": 34
}
]
},
{
"time_begin": "2020-09-04",
"time_end": "2020-09-11",
"department": "广告",
"dinnerStatistic": [
{
"dinner_id": 233,
"dinner": "下午茶",
"order_count": "13",
"order_money": 82
},
{
"dinner_id": 235,
"dinner": "宵夜",
"order_count": "14",
"order_money": 79
},
{
"dinner_id": 234,
"dinner": "晚餐",
"order_count": "8",
"order_money": 20
}
]
},
{
"time_begin": "2020-09-04",
"time_end": "2020-09-11",
"department": "技术",
"dinnerStatistic": [
{
"dinner_id": 233,
"dinner": "下午茶",
"order_count": "28",
"order_money": 413
},
{
"dinner_id": 239,
"dinner": "午餐",
"order_count": "1",
"order_money": 7
},
{
"dinner_id": 241,
"dinner": "早餐",
"order_count": "107",
"order_money": 965.42
}
]
}
]
}
}
解决
但又不好意思麻烦后台大佬修改,于是决定自己先试试能不能变换数据结构。最后用上了解构与对象合并的方法成功解决:
let data=[]
let result=[...res.data.statistic].map(item=>{
//挑出父元素中你需要的属性,组成同一个新的对象,这里我去掉了dinnerStatistic
let one={time_begin:item.time_begin,time_end:item.time_end,department:item.department}
//遍历每个子元素
item.dinnerStatistic.map(info=>{
//这里用到了对象合并的方法:Object.assign(target, ...sources);
//让子元素与父元素合并成一个新对象
let entire=Object.assign({},one,info);
//将新对象加进data中
data.push(entire)
})
})
console.log(data)
最后的数据机构如下: