Home >Web Front-end >JS Tutorial >How to Convert CSV Data to a JavaScript Array of Objects?
How to Read CSV Data in JavaScript and Convert it to an Array
Problem:
You have CSV data with multiple columns. How do you read this data using JavaScript and convert it into an array where each object represents a row with key-value pairs?
Example CSV Data:
heading1,heading2,heading3,heading4,heading5 value1_1,value2_1,value3_1,value4_1,value5_1 value1_2,value2_2,value3_2,value4_2,value5_2 ...
Desired Output Array:
[ { heading1: 'value1_1', heading2: 'value2_1', heading3: 'value3_1', heading4: 'value4_1', heading5: 'value5_1' }, { heading1: 'value1_2', heading2: 'value2_2', heading3: 'value3_2', heading4: 'value4_2', heading5: 'value5_2' }, ... ]
Solution:
Using the jQuery-CSV library, you can easily convert the CSV data into an array of objects:
Step 1: Add Line Breaks
Ensure that your CSV data has line breaks to make it valid.
Step 2: Use the $.csv.toObjects() Function
var data = $.csv.toObjects(csv);
Output:
The data variable will contain an array of objects representing the rows in the CSV data, with key-value pairs for the headings and their corresponding values.
Note: For more flexibility and compatibility, the jQuery-CSV library is recommended over the code sample you provided.
The above is the detailed content of How to Convert CSV Data to a JavaScript Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!