最近项目中有个需求需要将一个类似二维数组的数据矩阵转置(行转列)我通过查资料发现这是很简单的。只需要经过下面的处理就没问题了。但。。。
但是我发现我的数据是对象数组就是下面那样
原始数据tableRows
如何转化呢?我从刚才的二维数组行转列中获取到灵感只需要获取keys和数组中每一个对象的values就行了,然后再将二维数组以其中某行数据作为keys生成新的对象数组就ok了,下面是代码,欢迎进入我的博客网站查看代码详情:点击查看代码 www.front-end.xin/article/det…
transformDatas = (tableRows) => { if (!tableRows.length) return console.log("tableRows ", tableRows) let tansDatas = [] for(let i = 0; i < tableRows.length; i++){ let item = tableRows[i] if(i===0){ let keys = Object.keys(item) tansDatas.push(keys) } let values = Object.values(item) tansDatas.push(values) } console.log("tansDatas ", tansDatas) //二维数组行转列 var newArray = tansDatas[0].map(function (col, i) { return tansDatas.map(function (row) { return row[i]; }) }); console.log("newArray", newArray) //二维数组重新生成新的对象数组 let keyRow = newArray[5]//已行转列后,然后以其中任意一行作为新数组中每个对象的key let tansformNewData = [] for(let j= 0;j< newArray.length;j++){ let obj = {} for(let k=0;k<keyRow.length;k++){ obj[keyRow[k]+""] = newArray[j][k] } tansformNewData.push(obj) } console.log("tansformNewData", JSON.stringify(tansformNewData)) return tansformNewData } let tableRows = [ {"id":2,"createAt":1567055846000,"updateAt":1567055846000,"companyId":1,"frequency":"YEARLY","periodEnd":1567008000000,"netIncome":534,"depreciation":34,"adjustment":321,"changeAcc":563,"changeLiab":4566,"changeInv":33,"changeOther":98,"totalOpr":6778,"capitalExp":88,"investments":99,"otherInv":8,"totalInv":67,"dividePaid":664,"purchase":443,"netBorrow":2,"otherFinance":34,"totalFinance":56,"effectChange":null,"changeEqui":78}, {"id":5,"createAt":1567117746000,"updateAt":1567117746000,"companyId":1,"frequency":"YEARLY","periodEnd":1535558400000,"netIncome":53,"depreciation":3,"adjustment":2,"changeAcc":2,"changeLiab":3,"changeInv":235,"changeOther":435,"totalOpr":3,"capitalExp":34,"investments":34,"otherInv":34,"totalInv":53,"dividePaid":34,"purchase":34,"netBorrow":34,"otherFinance":34,"totalFinance":66,"effectChange":null,"changeEqui":66,} ] transformDatas(tableRows)复制代码
使用Object.keys(item)和 Object.values(item)取出keys和values后
对tansDatas进行行转列处理后
行转列后,我想以newArray[5] = ["periodEnd", 1567008000000, 1535558400000]作为新的对象数组的key以反映各个数据随periodEnd(周期结束时间点)变化的情况。当然你可以选择你想要的任意一行作为key。
生成以["periodEnd", 1567008000000, 1535558400000]为key的新对象数组
我们来看看转化前后对照图
这里以react项目antd table组件为例
<Table columns={columns} dataSource={data} />复制代码
行 → 列