Top way to extract JavaScript information from a basic 3-line CSV

I am grappling with a basic CSV file (imported via JQuery's $.ajax from the /data/league.csv on the same website) containing three lines in this specific structure:

"Kimberlin Library","Queen's Building","Innovation Centre","etc etc"
8,2,0,-2
1,0,-1,0

My goal is to transform it into this format (using building and percent as data points for the x-y axes in Highcharts, while also populating a list with all three entries):

var leaguetable = {
    building: ["Kimberlin Library","Queen's Building","Innovation Centre","etc etc"],
    percent: [8,2,0,-2],
    change: [1,0,-1,0]
};

It may seem like a trivial task, but I am struggling to find a solution despite attempting various techniques suggested by others (such as using split(/\r\n|\n|r/), exploring /^(.*)$/m, and referencing resources like this question). I am willing to start fresh and require the simplest possible approach, whether through JQuery or pure Javascript. In a previous scenario, I resorted to converting the file to JSON, but I prefer to avoid that route this time if feasible.

Answer №1

Give this a try for handling CSV files. The code uses a regex pattern to parse both simple CSV and CSV with single or double quotes. You'll need to adjust the end of processCSV() to fit your specific requirements as I'm only returning the object without any further action.

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "my_csv.txt",
        dataType: "text",
        success: function(data) {processCSV(data);}
     });
 });

function processCSV(allLines) {
    var allLinesArray = allLines.split(/\r\n|\n/);
    var leaguetable = { 'building': [], 'percent': [], 'change': [] };
    var pattern = /([^,'"]*"[^"]*"[^,'"]*)|([^,'"]*'[^']*'[^,'"]*)|([^,"']*)/ig;
    var fieldValues;

    for (var i=0; i<allLinesArray.length; i++) {
        fieldValues = allLinesArray[i].match(pattern);
        if (fieldValues) {
            for (var j=0; j<fieldValues.length; j++) {
                // Remove specified quotes if the value starts with single or double quote
                if (fieldValues[j].charAt(0) === '"' || fieldValues[j].charAt(0) === "'") {
                    fieldValues[j] = fieldValues[j].replace(fieldValues[j].substr(0,1), "");
                }
            }
            // Assuming correct number of fields in CSV, but consider adding validation
            leaguetable.building.push(fieldValues[1]);
            leaguetable.percent.push(fieldValues[2]);
            leaguetable.change.push(fieldValues[3]);
        }
    }
    return leaguetable;
}

Answer №2

If handling a straightforward CSV file, you may consider the following approach:

  1. Begin by separating the data into individual lines.
  2. For each line:
    1. Divide the line based on commas.
    2. Add the first section to the collection named building.
    3. Include the second section in the percent array, ensuring it is converted using parseInt.
    4. Repeat this process for the third part and store it in the change 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

In Vue, emitting does not trigger the parent component to update its properties

The emit is functioning properly, as I can observe in the vue developer tool. However, the property in the parent element is not updating. Child Component: <template> <div> <ul> <li v-for="(option, index) in opt ...

Tips for sending all values of an array in JSON format as a parameter to a URI endpoint using a loop

I have been attempting to extract the JSON response value and assign it as an environment variable. To do this, I am iterating through the values retrieved from the JSON. However, I am facing difficulty in passing the values from each array index to the ...

Exploring CountUp functionality with Vue framework

I'm still getting the hang of Vue and recently completed my first project following a tutorial. This project is my first solo endeavor. Currently, I am working on a basic page to display the scores between two teams. The scores are retrieved from an ...

Leveraging x-template in VueJS to create a sub-component within a larger component

I'm having trouble understanding how to properly use x-template for a subcomponent within a VueJS component. My component, CategoryNav.vue, has a template that uses an x-template to display a list. However, when I render the page, the component creat ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

How to reference an image located in one folder from a page in a different folder using React

Imagine there is Folder A containing an image called 'image.jpg' and Folder B with an HTML page that needs to access the image in Folder A in order to display it. The following code successfully accomplishes this task: <img src={require(&apo ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

What is the best way to show only the weekdays on the x-axis?

My goal is to create a scatter-linked graph using D3.js, showcasing the people count for various shifts on different dates in January 2020. Here is the code snippet I am working with: <!DOCTYPE html> <html lang="en" > <head> & ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

How can TypeScript rules be incorporated into a Next.js project without compromising next/core-web-vitals?

In my current NextJS project which is in typescript, I have the following configuration in my .eslintrc.json: { "extends": "next/core-web-vitals" } Now, I want to include additional typescript rules, such as enforcing the rule of n ...

Adding markers to a Leaflet map using coordinates retrieved from a Supabase database - a step-by-step guide

I am looking to incorporate markers on a map using coordinates stored in a Supabase database column. Below is my Vue code: <l-marker v-for="(marker, index) in markers" :key="index" ref="markersRef" :lat-lng="marker.po ...

Exception encountered during JSON conversion in Spring MVC REST API

I am currently working on implementing a basic Spring MVC REST example. When sending a PUT request, I encountered the following exception: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "propert ...

Creating a class dynamically in Angular 2 Typescript based on a property value

How can I dynamically assign classes in HTML based on a property in Angular 2 without using jQuery or Bootstrap? I am trying to open a dropdown list. Here is what I have: <li class="dropdown mega-menu mega-menu-wide" //stuck at adding class of op ...

Using an HTML element to pass a variable into a replace function

I am looking to highlight a 'SearchString' by replacing it with <span style="background-color: yellow">SearchString</span> within a targetString. The SearchString varies, so I am wondering how I can make this happen. This is what I ...

Ways to extract specific HTML from a jQuery element

When fetching html from a website, how can I extract specific html content instead of getting all of it? I have attempted the following method: Before appending data to the target below container.html(data); I would like to perform something like data.f ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Utilizing a Variety of Animations with D3 (version 5)

I am currently working on an animation that involves fading out text in a list and collapsing the list when the heading is clicked. However, I am facing a few issues with the code provided in this example. d3.select('.panel-heading') .on(&apos ...

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

Switch image on click (toggle between pause and play buttons)

Having some difficulty setting up a 3D audio player in A-Frame where the pause and play button images need to change depending on whether the audio is playing or not. Interested in seeing my code in action? Check it out here. ...