0

I'm trying to convert CSV data into paring array data, but I'm totally new to javascript, and I don't know how to do it now. Does any one have some idea? Thanks in advance!

CSV data:

year,USA,EU,UK,China,India
2003,10882,10970,1795,1575,599
2002,10383,9040,1564,1434,510
2001,10020,8303,1430,1345,479
2000,9762,8234,1438,1252,457
1999,9213,8901,1460,1158,447
1998,8720,8889,1423,1148,414

Object array data:

[{
  label: "USA",
  data: [[2003, 10882],
   [2002, 10383],
   [2001, 10020],
   [2000, 9762],
   [1999, 9213],
   [1998, 8720]]
 },

 {
  label: "EU",
  data: [[2003, 10970],
   [2002, 9040],
   [2001, 8303],
   [2000, 8234],
   [1999, 8901],
   [1998, 8889]]
 },

 {
  label: "UK",
  data: [[2003, 1795],
   [2002, 1564],
   [2001, 1430],
   [2000, 1438],
   [1999, 1460],
   [1998, 1423]]
 },

 {
  label: "China",
  data: [[2003, 1575],
   [2002, 1434],
   [2001, 1345],
   [2000, 1252],
   [1999, 1158],
   [1998, 1148]]
 },

 {
  label: "India",
  data: [[2003, 599],
   [2002, 510],
   [2001, 479],
   [2000, 457],
   [1999, 447],
   [1998, 414]]
 }]
1
  • Does it need to be Javascript? Can you use a server side language? Commented Sep 9, 2010 at 7:55

1 Answer 1

0

You need to split your lines using .split("\n") function, with it you'll get this array

['year,USA,EU,UK,China,India',
'2003,10882,10970,1795,1575,599',
'2002,10383,9040,1564,1434,510',
'2001,10020,8303,1430,1345,479',
'2000,9762,8234,1438,1252,457',
'1999,9213,8901,1460,1158,447',
'1998,8720,8889,1423,1148,414']

Now you iterate this array .split again at ,. You should get this after doing it:

[
    ['year','USA','EU','UK','China','India'],
    ['2003','10882','10970','1795','1575','599'],
    ['2002','10383','9040','1564','1434','510'],
    ['2001','10020','8303','1430','1345','479'],
    ['2000','9762','8234','1438','1252','457'],
    ['1999','9213','8901','1460','1158','447'],
    ['1998','8720','8889','1423','1148','414']
]

Now all you have to do is to iterate over this in a two level nested for loop, and build the object you want out of it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Could you give me an example showing how to do it generally?
You're welcome :) Try to give it a shot using the split function, and test the two nested loop things, if something fails or you couldn't do, you can ask about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.