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?
1 Answer 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');
answered Sep 16, 2019 at 9:19
Swaroop Deval
9186 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
EddiGordo
"fs" is not known in this context...
Swaroop Deval
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. nodejs.org/api/fs.html
lang-js