Fetch information from DataObject's CSV file using JavaScript

After reading a csv file with the following code:

var x="dema.csv";
loadCSV(x);

function loadCSV(file) {
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari
        var request = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        var request = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // load
    request.open('GET', file, false);
    request.send();
    parseCSV(request.responseText);
}

I used the next piece of code to put the data into a dataObject:

function parseCSV(data, dataArray) {
    //replace UNIX new lines
    data = data.replace(/\r\n/g, "\n");
    //replace MAC new lines
    data = data.replace(/\r/g, "\n");
    //split into rows
    var rows = data.split("\n");

    // loop through all rows
    for (var i = 0; i < rows.length; i++) {
        // this line helps to skip empty rows
        if (rows[i]) {
            // our columns are separated by comma
            var column = rows[i].split(",");


            var date=column[0];
            var value = column[4];
            var dataObject = {
                date: date,
                T4: value
            };
        
            dataArray.push(dataObject);
        }
    }

}

When extracting only the date and T4 columns, I encountered an issue. I am looking for a way to process the data, potentially using loops to validate certain conditions (e.g., ensuring that T4 does not exceed 700 over a 30-second period). Should I stick with using a dataObject or switch to a 2D array? What is the best tool for accessing cell contents in this scenario?

Answer №1

var file = "data_file.csv";
var dataRows = [];

loadDataFromFile(file);

function loadDataFromFile(file) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            processData(this.responseText, dataRows);
            window.alert(dataRows[0].cycle);
        }
    };
    request.open("GET", file, true);
    request.send();
}

function processData(data, array) {
    data = data.replace(/\r\n/g, "\n");
    data = data.replace(/\r/g, "\n");
    var rows = data.split("\n");

    for (var i = 0; i < rows.length; i++) {
        if (rows[i] && i > 0) {
            var columns = rows[i].split(",");
            var dataObject = mapValuesToObjects(columns);
            array.push(dataObject);
        }
    }
}

function mapValuesToObjects(csvLine) {
    var absTimeValue = csvLine[0];
    var timeValue = csvLine[1];
    var topsValue = csvLine[2];
    var cycleValue = csvLine[3];
    var T4Value = csvLine[4];
    var testValue = csvLine[5];
    return {
        absoluteTime: absTimeValue,
        time: timeValue,
        tops: topsValue,
        cycle: cycleValue,
        T4: T4Value,
        test: testValue
    };
}

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

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

Validating dates using JQuery within a specific range of dates

Users can input a date within a specified range in an input field. To enable this feature, I created a new method using the jQuery validator object: $.validator.addMethod("dateRange", function(value, element, from, to){ try { var date = new D ...

Trigger a function upon clicking a DOM element in Vue.js

My goal is to trigger a function whenever I click on elements in the DOM that have a specific class. Despite my efforts, the functionality doesn't seem to work, and no errors are being reported. Here's the relevant code: methods: { ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

Learning how to integrate Next.js, React.js, and Redux into an HTML page for an enhanced user

My current project is built on Asp.Net MVC, but the technology used is not crucial. I integrated react.js and redux for searching a section of my html page using a cdn link. Now, I am considering deploying the server side of the application with next.js. ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

AngularJS checkbox feature to tally the number of items that are currently selected or unselected

How can I use angularjs to count the number of selected and unselected checkbox items? My HTML <label class="col-xs-5 pull-left" style="font-weight: bold; margin-left: 4px; margin-top: -17px;" >You have selected <font size="3" color="green" ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

Trouble with AngularJS ui-router: template fails to show up

I have been diving into a tutorial on egghead.io that delves into application architecture, tweaking certain components to fit my specific application needs. Just a heads up, I am relatively new to Angular, so I'm hoping the issue at hand is easy to ...

The onWrite cloud function does not activate upon the creation of a new document

I have a collection called 'Users' that stores documents with user objects as well as a sub-collection named 'Notifications'. When a new notification is generated for a user, a corresponding document is created in the 'Notification ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

Tips for transmitting data from the server to the client side

From the code posted below, I am attempting to transfer the value access_token from the method fetchAuthenticationToken to the method fetch in Ws.js. In fetchAuthenticationToken, I receive the value for the access_token and then assign that value to both r ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...

Triggering a jQuery click event to showcase the hidden content

I am attempting to replicate the functionality seen on the website. The issue I am facing is related to the event_content class. I want to display only a limited amount of content initially, and then hide the excess content. Upon clicking the plus class, ...

"findByIdAndUpdate continues to work successfully even when the request body includes parameters that are not defined in

Referenced from This particular tutorial on MERN stack development... In my mongoose schema, I have defined 4 fields: const mongoose = require('mongoose'); const Schema = mongoose.Schema; let Todo = new Schema({ name: { type: String ...

The Django Rest Framework appears to be lacking the functionality to allow image uploads, despite the presence of an ImageField in the model

Having trouble with Django Rest Framework as it doesn't display the option to upload images. I have an imageField in my models but when I try to create a new item by visiting the API URL, I receive a GET http://127.0.0.1:8000/api/person-create/ 405 (M ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...

Expanding Headers with JavaScript

Looking to add a Stretchy Header Functionality similar to the one shown in this GIF: Currently, on iPhones WebView, my approach involves calling a Scope Function On Scroll (especially focusing on Rubberband Scrolling) and adjusting the Image Height with C ...