1

imagine that you have csv data like this that I can read them from a textarea on my web page:

A,10,USA
B,5,UK
A,2,USA

I am trying to use cs-jQuery to parse and process this data to get the following report:

A has ran 12 miles with average of 6. 
B has ran 5 miles with average of 5. 

The code that I have written looks like this:

<script>
$(document).ready(function() {
    $('#calculate').click(function() {
        $('#report').empty();
        var data = $('#input').val();
        var values = $.csv.toObjects(data);
        $('#report').append(values);
        alert(values);
    });
});
</script>

but all I am getting is [object Object] [object Object]... any suggestion on what I should do? any way to do this with jQuery functionality?

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
Payam
  • 741
  • 3
  • 14
  • 37

1 Answers1

2

this function $.csv.toObjects() return array of objects

Useful for parsing multi-line CSV data into an array of objects representing data in the form {header:value}. Unless overridden, the first line of data is assumed to contain the headers.

You don't have header so you should use $.csv.toArrays() instead and iterate over that array:

$.each($.csv.toArrays(data), function(_, row) {
   $('#report').append('<div>' + row[0] + ' has ran ' + row[1] + ' miles</div>');
});

if you want to use toObjects you need to put header

person,miles,country
A,10,USA
B,5,UK
A,2,USA

and access it using row.person row.miles and row.country

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • oh, nice. the documentation of csv-jQuery is so poor. This is very helpful.Thanks. I just have to find a way to create a Hashmap of the data to count for the average. – Payam Mar 18 '13 at 15:37
  • you can count averge using something like: `var sum = 0; for (var i=data.length;i--;) { sum+=data[i][1]; } var average = sum/data.length;` – jcubic Mar 18 '13 at 15:43
  • It might be too much, but I think you need to create a Hashmap that its index is the name (A,B,...) and the values are the total miles and the average. – Payam Mar 18 '13 at 16:24
  • @user843681 if you still have problems you should ask another question. – jcubic Mar 18 '13 at 16:29