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?

0

1 Answer 1

-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');
Sign up to request clarification or add additional context in comments.

2 Comments

"fs" is not known in this context...
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.