我们在渲染表格时,通常需要的数据格式必须得是一维数据,如果是给的我们二维数据格式那我们需要给数据进行转换一下,把二维数据中的字段转换出来,将二维数组转换成一维数组。
二维数据格式:
[
{
code: "20180801",
date: [{time: "2022-10", amts: "258"}],
name: "道家学派",
numbers: "226"
},
{
code: "20180802",
date: [{time: "2022-07", amts: "116"} ],
name: "鬼谷子学派",
numbers: "184",
},
{
code: "20180803",
date: [{time: "2022-07", amts: "129"},
{time: "2022-08", amts: "112"}],
name: "江左盟",
numbers: "112",
}
]
下列方法主要使用了ES6中的属性Object.assign()的方法,通过map循环获取到二层数据,并利用对象中的属性obj[key] 给变量赋值,obj里面是变量名,等号左边赋值
translate(source) {
let obj = {};
this.newData = []
source && source.map(el => {
obj = {}
el.date.map((item, index) => {
obj[`custMonthAmt-${item.time.slice(-2)}`] = item.amts;
});
this.newData.push(Object.assign({}, el, obj))
return this.newData
})
},
转化后一维数据格式:
[
{
'custMonthAmt-10': "258",
code: "20180801",
date: Array(1),
name: "道家学派",
numbers: "226"
},
{
'custMonthAmt-07': "116",
code: "20180802",
date: Array(1),
name: "鬼谷子学派",
numbers: "184",
},
{
'custMonthAmt-07': "129",
'custMonthAmt-08': "112",
code: "20180803",
date: Array(2),
name: "江左盟",
numbers: "112",
}
]
注:不了解Object.assign用法的小伙伴可以去他的博客逛逛呦 →