Home > Web Front-end > JS Tutorial > How to Convert CSV Data to a JavaScript Array of Objects?

How to Convert CSV Data to a JavaScript Array of Objects?

Mary-Kate Olsen
Release: 2024-12-14 22:48:11
Original
939 people have browsed it

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
...
Copy after login

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' },
    ...
]
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template