Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object.

The API requires the data to be structured like this:

"data": [
        {
            "id": 1,
            "nombre": "AGUASBLANCAS-AGB",
            "descripcion": "-",
            "it_unidad_generadora": 0
        },
        {
            "id": 425,
            "nombre": "AGUASBLANCAS-AGBQ",
            "descripcion": "-",
            "it_unidad_generadora": 403
        }
    ]

However, after using Papaparse, the csv gets converted into an array of arrays representing each row like this:

"data":  [
    0: ["ID", "NOMBRE", "DESCRIPCIÓN", "IT UNIDAD GENERADORA"]
    1: ["1", "AGUASBLANCAS-AGB", "-", "0"]
    2: ["425", "AGUASBLANCAS-AGBQ", "-", "403"]
    ]

I am looking for a way to transform this into a JSON array of objects using Papaparse, rather than an array of arrays representing each row. Can anyone provide guidance on achieving this?

Answer №1

For more information, check out the documentation at:

To convert the result into an array of objects, all you need to do is set header: true in the options.

const parsedData = Papa.parse(data, { header: true });

Answer №2

Try out a different library instead of Papaparse, such as https://www.npmjs.com/package/csvtojson

This alternative library has garnered impressive download numbers and might be just what you need for handling your data.

Answer №3

Here is how I tackled the problem:

I employed Papa.parse(event.target.files[0], {complete: async results => {
    let keys = results.data[0];
    // My goal was to eliminate special characters, spaces, and more
    keys = results.data[0].map(v => v.toLowerCase().replace(/ /g,"_").normalize('NFD').replace(/[\u0300-\u036f]/g,""));

    let values = results.data.slice(1);
    let objects = values.map(array => {
      let object = {};
      keys.forEach((key, i) => object[key] = array[i]);
      return object;
    });
    // I then proceeded to call my API with the data successfully
    await uploadCSV(type, objects);
  }
});

Although it wasn't related to Papaparse configuration, I used JavaScript to generate objects with specific keys extracted from the first row of the array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

Accessing a jstl variable within javascript script

I need to access a JSTL variable within a JavaScript function. The JavaScript code submits a form. $("#userSubmit").on('submit', function () { document.getElementById("userForm").submit(); }); In the server-side code - request.setAttribu ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached . My de ...

Is it possible to omit certain columns when extracting data from a Kendo grid?

My challenge involves extracting data from a Kendo grid using the following JavaScript call: var data = JSON.stringify($(".k-grid").data("kendoGrid").dataSource.data()) This retrieves all properties in the C# class for the records. There are three proper ...

Convert the Java.util.Map into a JSON schema declaration

Struggling to find a simple solution, I'm looking to convert a java.util.Map instance into a JSON schema that can be recognized by the org.jsonschema2pojo Maven plugin in order to generate a POJO. I’ve hit a roadblock with this task and could reall ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

What's the deal with peculiar symbols and PHP's Json_Encode?

I've encountered an issue while using JSON_ENCODE in PHP to display data. When it comes across the word: Æther, it prints out as \u00c6ther. Does anyone have a solution for making the JSON output show that character correctly, or will I need to ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

Tips for optimizing Firestore database requests on the web to minimize the number of API calls

On my product page, every time a user presses F5, the entire list of products gets loaded again. I am looking for a way to save this data locally so that it only needs to be updated once when a new product is added, instead of making multiple API calls. ...

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

Looping through objects and updating state based on a filter condition

Within my React state, there exists an array of objects similar to the following: timers: { id:"-LL-YVYNC_BGirSn1Ydu" title: "Project Title" project: "Project Name", elapsed: 0, runningSince: 0, }, { id:"-LL-YVYNC_BGirSn1Ydu-2", ...

How to extract data from a JSON file in Java without relying on org.json library

I need help extracting the first element in the "key" array and its corresponding value from the given JSON data. I have come across examples using org.json, but it seems outdated. Can anyone suggest the best way to achieve this with the provided JSON file ...

Learn how to access an array within an object using JavaScript and an API URL

Trying to fetch data from the swapi API to display film titles using jQuery. Below is the JavaScript code: $(function(){ function promiseTest(){ return $.ajax({ type: 'GET', url: 'https://swapi.co/api/people/', } ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

AngularJS Component enthusiasts

While going through a tutorial on the Angular UI Router GitHub page (link: https://github.com/angular-ui/ui-router), I came across an intriguing code snippet: var myApp = angular.module('myApp', ['ui.router']); // For Component users, ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

Using nodeJS's util module to format and pass an array

I've been using util.format to format strings like this: util.format('My name is %s %s', ['John', 'Smith']); However, the second parameter being an array ['John', 'Smith'] is causing issues because m ...