我需要将此CSV数据转换为javascript数组:
5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,"defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,"defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,"defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,"defgv",home
我尝试使用:
var dataArr = xmlData.split("\n");
var data = dataArr.splice(1,dataArr.length-1);
但是它不起作用。.由于字符defgv中的空格,请考虑一下它。请您帮我转换一下。
预期输出:-
["5/27/2019 9:54:09,5/27/2019,GSCOH6EUYN77D5N5HB22222222,defgv,street",
"5/27/2019 20:21:58,5/27/2019,OMAFNGTWEITTD333333333,defgv,apartment"]
相反,m收到的输出为:
0: "5/22/2019 17:10:08,5/22/2019, GSCOH6EUYN77D5N5HB22222222,""
1: " defgv",street
"
2: "5/22/2019 17:24:19,5/22/2019, OMAFNGTWEITTD333333333,""
3: " defgv",apartment
"
答案 0 :(得分:0)
我不清楚您的输入格式是什么。但是,请猜测一下,您可能必须拆分成字符串,然后将成对的字符串组合成单个字符串。这样可以做到:
const splitIntoJointRows = (data) => data .split ('\n')
.reduce ((a, s, i, ss) => i % 2 ? [...a, ss[i - 1] + s] : a, [])
//-------------------------------------------------------------------------
const data = `5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,
"defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,
"defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,
"defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,
"defgv",home
`;
console .log (
splitIntoJointRows(data)
)
console .log (
splitIntoJointRows(data)
.map(s => s.split(/,\s*/))
)
console .log (
splitIntoJointRows(data)
.map(s => s.split(/,\s*/))
.map(([date, a, b, c, d]) => ({date, a, b, c, d}))
)
在该代码段中,还有一个调用,使用该调用可以构建一个由字段数组组成的数组,并且可以将其进一步转换为对象数组(具有已发明键)。