Ole
Ole

Reputation: 47018

Convert Papaparse rows to objects

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

Upvotes: 2

Views: 2764

Answers (2)

banjeremy
banjeremy

Reputation: 311

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,
  },
]

Upvotes: 2

ShivamRajput
ShivamRajput

Reputation: 166

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

Upvotes: -1

Related Questions