0

I am javascript noob. I need from csv files to javascript object.

<<1.csv>>
apple
banana
car

<<2.csv>>
apple
banana

<<3.csv>>
apple
car
day

<<4.csv>>

<<5.csv>>
car

I want to get something like this.

x = { "first": ["apple", "banana", "car"],
      "second": ["apple", "banana"],
      "third": ["apple", "car", "day"],
      "fourth": [],
      "fifth": ["car"]
}

What should I do for it?

홍기김
  • 5
  • 3

1 Answers1

-1

Below is the sample code.

var x = {};

function readCSV(filename, objectKey) {
    var bufferString; 
    fs.readFile(filename,function (err,data) {
        if (err) {
            return console.log(err);
        }

        //Convert and store csv information into a buffer. 
        bufferString = data.toString();

        //create an array that contains each line as an element
        x[objectKey] = bufferString.split('\n');
    });
}

readCSV('1.csv', 'first');
readCSV('2.csv', 'second');
readCSV('3.csv', 'third');
readCSV('4.csv', 'forth');
readCSV('5.csv', 'fifth');
Swaroop Deval
  • 906
  • 5
  • 22
  • "fs" is not known in this context... – EddiGordo Sep 16 '19 at 09:25
  • are you running it on node or browser? If you are running on browser where are you keeping the files? The above code is a sample if you are executing the task on node server. https://nodejs.org/api/fs.html – Swaroop Deval Sep 16 '19 at 09:27