2

Does papaparse support return an array of object instances that are keyed by the header columns?

For example I have a CSV file like this:

sku, location, quantity
'sku1', 'Chicago', 3
'sku2', 'New York, 4

I'd like the array returned by papaparse to look like this:

 [{sku: 'sku1', location: 'Chicago', quantity: 3}, ...]

This should also be possible:

results[0].sku == 'sku1'
results[1].quantity == 4
Ole
  • 41,793
  • 59
  • 191
  • 359

2 Answers2

2

Try adding header: true to the config parameter.

From the docs:

header: If true, the first row of parsed data will be interpreted as field names. An array of field names will be returned in meta, and each row of data will be an object of values keyed by field name instead of a simple array. Rows with a different number of fields from the header row will produce an error. Warning: Duplicate field names will overwrite values in previous fields having the same name.

For example:

Papa.parse('./data.csv', {
  download: true,
  header: true, // gives us an array of objects
  dynamicTyping: true,
  complete: ({ data }) => console.log(data),
});

given your data should yield

[
  {
    sku: 'sku1',
    location: 'Chicago',
    quantity: 3,
  },
  {
    sku: 'sku2',
    location: 'New York',
    quantity: 4,
  },
]
banjeremy
  • 301
  • 5
  • 13
-1

It is possible by few line in simple javascript working example:

My csv file data:

sku, location, quantity

'sku1', 'Chicago', 3

'sku2', 'New Yoark, 4
ShivamRajput
  • 146
  • 1
  • 5
  • Hi - I don't think this works. Here are some of the results I get when playing around with this: JSON.stringify(results.data); console.log(result.length);//124 var obj = result[0]; // console.log(obj.sku); //Undefined – Ole Apr 29 '17 at 18:03
  • use just need to write like result[0]['sku'] to access 'sku1' – ShivamRajput May 01 '17 at 06:49