JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Js对数组行列转化

2021. 08. 27    

JS对数组行列转化

arr = [
    [1, 2, 3],
	[1, 2, 3],
	[1, 2, 3]
]
arr = arr[0].map((col, i) => {
	return arr.map(row => {
		return row[i];
	})
});
console.log(JSON.stringify(arr))
/*
	[
		[1,1,1],
		[2,2,2],
		[3,3,3]
	]
*/

高阶

let res = {
  "code": 0,
  "data": {
    "respRelateVoList": [
      {
        "copyRespPriceList": [{ "toTotalPrice": 1, },{ "toTotalPrice": 2, },{ "toTotalPrice": 3, }],
      },
      {
        "copyRespPriceList": [{ "toTotalPrice": 4, },{ "toTotalPrice": 5, },{ "toTotalPrice": 6, }],
      }
    ],
  },
}

let data = res.data.respRelateVoList;
let len = data[0] && data[0].copyRespPriceList.length;
let arr = [];
for (let index = 0; index < len; index++) {
  arr[index] = []
}
data.forEach((item, i) => {
  item.copyRespPriceList.forEach((sitem, s) => {
    //sitem.schedule = item.copyRespScheduleMainVoList[s]
    arr.forEach((aitem, j) => {
      if (s % len == j) {
        aitem.push(sitem.toTotalPrice)
      }
    })
  })
})
console.log(arr);//[[1,4],[2,5],[3,6]]