Reading a csv file and convert it to Array of object , how to store the data retrieved to another array ? | JavaScript, Node.js, React.js and Angular.js Forum
S
Sivaranjani Sivakozhundhu Posted on 09/02/2021

class1.js

const csv = require('csv-parser')
const fs= require('fs')

var results =[];


getdatafromcsv(){

fs.createReadStream('data.csv')  ===> data.csv will have data row with comma seperated 
.pipe(csv({}))
.on('data',(data) => results.push(data))
.on('end',()=> {
console.log(results) ==> prints the data from CSv file in array format
});
return results;

}


class2.js

var inputdata = []

const lead_Helper = require('../lead_Common/lead_Helper')

inputdata = lead_Helper.getdatafromcsv();

console.log(inputdata ) ===> shows null value.

 

 

i need to assign results to some arrary and use it to another function . Please help.

 

 


Y
Yogesh Chawla Replied on 09/02/2021

You can also read csv file in javascript like this

function handleFiles() {

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "D:\Docs\Desktop\csvfile.csv",
            dataType: "csv",
            success: function (data) { processData(data); }
        });
    });
}

and convert to array like this:

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    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);
}

Please let me know if this helps in any way otherwise will find another solution.


Y
Yogesh Chawla Replied on 09/02/2021

This is how we can copy one Array to another:

var first =  [1, 2, 3];
var second = [4, 5];
 
for (var i of second) {
    first.push(i);
}
 
console.log(first);
 

Or

var first =  [1, 2, 3];
var second = [4, 5];
 
Array.prototype.push.apply(first, second);
console.log(first);
 
/*
    Output: [ 1, 2, 3, 4, 5 ]
*/


Y
Yogesh Chawla Replied on 09/02/2021

This is how we can copy one Array to another:

var first =  [1, 2, 3];
var second = [4, 5];
 
for (var i of second) {
    first.push(i);
}
 
console.log(first);
 

Or

var first =  [1, 2, 3];
var second = [4, 5];
 
Array.prototype.push.apply(first, second);
console.log(first);
 
/*
    Output: [ 1, 2, 3, 4, 5 ]
*/


Y
Yogesh Chawla Replied on 09/02/2021

This is how we can copy one Array to another:

var first =  [1, 2, 3];
var second = [4, 5];
 
for (var i of second) {
    first.push(i);
}
 
console.log(first);
 

Or

var first =  [1, 2, 3];
var second = [4, 5];
 
Array.prototype.push.apply(first, second);
console.log(first);
 
/*
    Output: [ 1, 2, 3, 4, 5 ]
*/