gpt4 book ai didi

javascript - 将字符串数组转换为对象 Javascript

转载 作者:行者123 更新时间:2023-11-30 10:58:09 25 4
gpt4 key购买 nike

我正在做的是我需要上传一个 .csv 文件并获取里面的数据,我检查并使用这个 code但是返回字符串数组我试图找到一种方法来转换它但我找不到一个

function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = ["Code", "LongName", "value", "dateFrom", "dateTo", "money"]

var lines = [];

for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {

var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}

console.log(lines);
upload(lines);
}

字符串数组(实际输出):

0: Array()
0: "Code:"'0000000001""
1: "LongName:"TEST1""
2: "value:0.0000"
3: "dateFrom:"07-10-2019""
4: "dateTo:"07-11-2019""
5: "money:0.0000"

预期输出:

0:
code: "0000000001"
longName: "TEST1"
value: 0.0000
dateFrom: "07-10-2019"
dateTo: "07-11-2019"
money: 0.0000

最佳答案

使用对象和括号表示法

function processData(allText) {
var allTextLines = allText.replace(/"/g, '').split(/\r\n|\n/);
var headers = ["Code", "LongName", "value", "dateFrom", "dateTo", "money"]

var lines = [];

for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {

var tarr = {};
for (var j = 0; j < headers.length; j++) {
tarr[headers[j]] = data[j];
}
lines.push(tarr);
}
}
console.log(lines);
//upload(lines);
}

processData('\n\"0000000001\",Test"1,0.0000,07-10-2019,07-11-2019,0.0000')

关于javascript - 将字符串数组转换为对象 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com