简体   繁体   中英

Convert String Array to Object Javascript

What I am doing is I need to upload a .csv file and get the data inside, I check and use this code but is return array of string i try to find a way to convert it but I can't find one

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);
}

Array of string(actual output):

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"

Expected Output:

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

Using object and bracket notation

 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')

What you can do is assign your array to an object with Object.assign()

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);
        }
    }
let objectOfLines=Object.assign({},lines)
    console.log(lines,objectOfLines);
    upload(objectOfLines);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM