Saturday, December 20, 2014

Use Javascript to upload csv file and chain replace method

Uploading the csv file was the easy part thanks to this code. (Just make sure you have appropriate code to display it since the author just uses console.log.)

Once the csv file was uploaded, my goal was to select certain rows and then, from those rows, select certain fields to display. We'll start with how the code to upload the csv file works.

Uploading the csv file:
Mounir Messelmeni's processData(csv) method takes the csv file you select as an argument and stores it in a variable as a string using split(). Once the string is appropriately split, the code then uses nested for loops to first split each record and then store each record as an element of an array. (You'll notice my code is slightly different regarding the separators I used.)

Regexp patterns
My problem was that I needed to access the individual fields within the records. That sounded a lot like accessing elements in an array, except I wasn't dealing with an array but an element in an array. Naturally, my first thought was to make each element its own array so I could access the fields as elements within the new array. You've probably already guessed the problem. When I created the new array and assigned an element to it, that didn't split anything up. I just had an array with one element.

I then considered separating each char and storing certain ones into an array and that array would then become an element in another array. That made me tired thinking about it. Plus, I still had the issue of figuring out how to target certain chars.

I also thought about saving the array element containing a record as a string, separating the string, and based on the separation, creating elements for an array. But I finally decided it was just easier to search for patterns. I am not claiming this is the best way, just that it is one way.

My code starts by storing lines.toString() in var x. I then create two patterns. (The csv file only contains 2 fields per record. For demonstrative purposes, text in both fields will be replaced.)

I also created an empty string, newstr which is then assigned the variable "x" with chained replace methods. The value of newstr becomes the value of the element with the id "list". I include an alert to show you the value of x before so you can compare that with the replace values.

The full code, including the csv file I used, is here.

No comments:

Post a Comment