Payam
Payam

Reputation: 751

how to parse csv by csv-jQuery and generate report?

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?

Upvotes: 1

Views: 667

Answers (1)

jcubic
jcubic

Reputation: 66590

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

Upvotes: 2

Related Questions