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

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

Mary-Kate Olsen
Release: 2024-12-07 09:04:11
Original
674 people have browsed it

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

How to Read Data from a CSV File Using JavaScript

Problem:

Convert CSV data into an array of objects, with headings as keys and values as the corresponding values, using JavaScript.

Sample 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:

[
    { 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:

Utilize the jQuery-CSV library, which offers a function called $.csv.toObjects(csv) that automatically maps CSV data to an array of objects.

Steps:

  1. Prepare the CSV data: Ensure the data is formatted as valid CSV, with line breaks.
  2. Include the jQuery-CSV library: Add to your HTML or JavaScript file.
  3. Parse the CSV data: Use the $.csv.toObjects(csv) function to convert the CSV data to an array of objects.

Code:

var data = $.csv.toObjects(csv);
Copy after login

Output:

The data variable will contain an array of objects with headings as keys and values as the corresponding values.

Note:

The original key-value mapping in the output array is technically invalid JavaScript. It should be wrapped in brackets, as shown in the above code example.

The above is the detailed content of How to Convert CSV Data to an Array of JavaScript 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