我正在处理数据,我需要一个在数据处理完成后将转置的函数。现在数据看起来像这样。
var string ='"EMAIL","PHONE","ADDRESS","AREA"
"something@gmail.com","1 123 456","Some St. 1","700"
"something1@gmail.com","1 123 789","Some St. 2","800"
"something2@gmail.com","1 123 654","Some St. 3","900"
"something3@gmail.com","1 123 987","Some St. 4","1000" ';
我需要一个将这些数据转换为以下内容的函数:
var string = '"EMAIL","something@gmail.com","something1@gmail.com","something2@gmail.com","something3@gmail.com"
"PHONE","1 123 456","1 123 789","1 123 654","1 123 987"
"ADDRESS","Some St. 1","Some St. 2","Some St. 3","Some St. 4"
"AREA","700","800","900","1000"';
答案 0 :(得分:2)
将数据作为字符串转换为2D数组(或表,矩阵等),然后可以transpose the matrix并将其连接回字符串:
const transpose = array => array[0].map((col, i) => array.map(row => row[i]));
const result = transpose(
data.split("\n").map(row => row.split(","))
).map(row => row.join(",")).join("\n");