-2

I have a csv file containing entries as follows:

a,10
b,20
c,30
d,40

In JavaScript, I want to assign this csv file to a variable lets say x as follow:

x = [
 ['a',10],
 ['b',20],
 ['c',30],
 ['d',40]
]

Can someone tell me how i can do this.

Brigand
  • 84,529
  • 20
  • 165
  • 173
pradeepchhetri
  • 2,899
  • 6
  • 28
  • 50
  • possible duplicate of [Javascript code to parse CSV data](http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data). Please search before asking. That was the first result for "javascript csv". – Brigand Aug 03 '13 at 22:37

1 Answers1

1

If your CSV is really that simple, you just need two splits and a loop:

var rows = "a,10\nb,20\nc,30\nd,40".split('\n');
var x = [];
for(var i=0; i<rows.length; i++) {
    x.push(rows.split(','));
}

A shorter version:

var x = "a,10\nb,20\nc,30\nd,40".split('\n').map(function(val) {
    return val.split(',');
});
bfavaretto
  • 71,580
  • 16
  • 111
  • 150