1

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
Newbie
  • 55
  • 6

2 Answers2

2

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')
User863
  • 19,346
  • 2
  • 17
  • 41
  • I have updated my question sorry if i type a wrong output. I have tried your code but can this work with the updated output above? Thanks sir. – Newbie Dec 04 '19 at 05:53
1

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);
}
kapil pandey
  • 1,853
  • 1
  • 13
  • 26