0

So I'm trying to parse a csv file using papaparse in Meteor, the following is the code:

var csv = Assets.getText('test.csv');

Papa.parse(csv, {
header:true,
complete: function(results) {
    results.data.forEach(row){

    }
    console.log(results);
}
});

It's giving me an unexpected token, expected ";" error on the results.data.forEach(row){ line. If I put for example var testword = 'x'; inside the brackets I get the same error. I was trying to loop through each row but I'm not sure why It's not letting me do so. Any ideas?

Rew
  • 175
  • 7
  • 1
    `forEach` expects a function, so either use an arrow function (`forEach(row => {...})` or `forEach((row) => {...})`) or use the function keyword (`forEach(function(row) {...})`). Your syntax is invalid (block after expression). – MasterAM Mar 07 '18 at 06:24
  • This works, however how do I access a particular part of the 'row' data? I've tried doing `row => ('ColumnName')` but that doesn't seem to work (returns null)? – Rew Mar 07 '18 at 17:42

1 Answers1

1

In situations like this it's always useful to do a search for the documentation of the function you are using. In this case the forEach function. Docs are here

Your mistake is that you are not passing a callback function to forEach as the first argument.

Modify your code to the following:

results.data.forEach(function(row) {
    // now you can loop through each row in here
});

As pointed out by MasterAM above, if you are using ES6 you can also use an arrow function to make this shorter:

results.data.forEach((row) => {
    // loop through each row here
});
Sean
  • 2,609
  • 1
  • 18
  • 34
  • This works, however how do I access a particular part of the 'row' data? I've tried doing `row => ('ColumnName')` but that doesn't seem to work (returns null)? – Rew Mar 07 '18 at 17:42
  • 1
    In this context row will be whatever is contained at that part of the array. If that is an object you can access the keys of that object using dot notation. E.g. `row.ColumnName`. Try `console.log(row)` so you can see what it prints out – Sean Mar 07 '18 at 17:45