Guide to converting a string into an undefined type

I've been working on parsing a csv file:

    let lines = csvData.split(/\r\n|\n/);
    let headers = lines[0].split(',');
    for (let i = 1; i < lines.length; i++) {
      let values = lines[i].split(',');
      let item = {};
      for (let j = 0; j < headers.length; j++) {
        item[headers[j]] = values[j];
      }
      items.push(item);
    }
    return items;

Now, the issue I'm facing is that all the data extracted from the csv file are in string format. I want to convert them into JSON and remove their type so that I can assign them to variables with different types. However, since I don't know the specific type of each variable, I can't directly use parseInt or parseFloat.

Every time I try to parse the values into JSON, they end up being strings like "1234" instead of integers like 1234. Usually, passing JSON data without specifying types works fine, but after converting the csvData into JSON, everything becomes a string. I suspect this might have something to do with the split function converting it into a string?

In terms of a solution, I thought about passing the type as an argument to the function, like readCsvFile<T>(csvData), and then checking if I can do something like this:

    if (typeof(T[headers[j]]) == 'number') {
      item[headers[j]] = parseFloat(values[j]);
    } else {
      item[headers[j]] = values[j];
    }

However, attempting T[header[j]] doesn't pass the compilation process.

Answer №1

I prefer to implement a more efficient solution.

//Declare variables
var csvData = "value1a,value2a,value3a\r\nvalue1b,value2b,value3b";
var objectsArray = [];
var lines = csvData.split(/\r\n|\n/);

//Split fields logic
var splitFields = function(line){
  let fields = line.split(',');
  createObject(fields);
}

// Assign field values and format the object
var createObject = function(fields){
  let obj = {};
  obj.field1 = fields[0];
  obj.field2 = fields[1];
  obj.field3 = fields[2];

  objectsArray.push(obj);
}

// Iterate through each line of CSV data
lines.forEach(splitFields);

//Display objects with assigned field values.
console.log(objectsArray);

Answer №2

If you find yourself in a situation where you don't need to identify the type of a property (and you're not actively seeking to access the value with an unknown type), consider utilizing the "unknown" type as outlined in this resource.

Using the "unknown" type is a more efficient approach compared to using "any," allowing you to specify the data type precisely when necessary.

Answer №3

Consider using 'any' as the type for all attributes.

// Define the properties from the CSV
class DataFromCSV {
  value1: any;
  value2: any;
}

...
let lines = csvData.split(/\r\n|\n/);
    let headers = lines[0].split(',');
    for (let i = 1; i < lines.length; i++) {
      let values = lines[i].split(',');

      // Instantiate here
      let item = new DataFromCSV();
      for (let j = 0; j < headers.length; j++) {
        item[headers[j]] = values[j];
      }
      dataItems.push(item);
    }
    return dataItems;

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

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Step-by-step guide to designing a leaflet map using Angular Formly

I am faced with a challenge to incorporate a leaflet map into an angular form using formly, and being new to this formly framework is making it difficult for me. Previously, I was able to integrate the map with regular HTML in angular as shown below: map ...

What is the best way to access all of the "a" elements contained within this specific div?

Chrome websites are built using the following structure: <div class="divClass"> <a class="aClass"></a> <a class="aClass"></a> <a class="aClass"></a> </div> Utili ...

The presence of foreign collections does not appear to be reflected in the combined data

I am developing a basic forum and I'm looking to connect two databases so I can show information about the user who created a post on that post: User.js: _id:60ccb13a21d65f0c7c4c0690 username: testuser name: test And Createpost.js _id:60d80b1305dcc5 ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

What is the process by which React recreates the React element tree (virtual DOM) with every state update?

From what I've gathered, every time a state is updated in React, it generates the react element tree (virtual DOM) and then compares it with the new one using a diffing algorithm. However, there's something I find puzzling. Let's say we hav ...

Every time I attempt to create a new ionic project using angular through the console, I encounter the error message: "npm ERR! Cannot read properties of undefined (reading 'isServer')"

Having an issue with npm where it is giving the error "Cannot read properties of undefined (reading 'isServer')." I have updated npm to the latest version and tried force-clearing the cache, but the issue persists. Can anyone provide assistance? ...

Issue encountered while attempting to write to csv-file using npm csv-writer - no error message displayed and function not working as

In my electron renderer.js process, I am attempting to write to a CSV file. Unfortunately, most of the time, the writing process doesn't work as expected, and the addition of .then is not executed. Despite this, no error messages or indications of mis ...

The onSubmit function in Formik fails to execute if there are no input values present

I am currently working on building a form using Next.js, TypeScript, and the Formik + Yup libraries. I've encountered two scenarios: one where an input field is visible and Formik captures the value, and another where the input is not visible and the ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Node installation failed due to npm encountering an ETIMEDOUT error

Recently, I've been encountering some obstacles while attempting to install npm on our office's laptop within a specific directory. An error message keeps popping up: npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT np ...

Utilizing ES6 Proxy leads to the occurrence of an error message stating "this is not a function" whenever a function call

As I ventured into the depths of ES6 Proxies, attempting to be a crafty developer, I found myself entangled in their complexities. My goal was to intercept any get or set operation on a property from a class I had written and ensure that they were stored e ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

This code encountered an Uncaught SyntaxError due to an invalid or unexpected token

Hey there, I've been struggling with an Uncaught SyntaxError: Invalid or unexpected token issue whenever I try to click on the edit or delete button. Can someone please help me figure out what's wrong with this code? I've spent hours looking ...

Searching through the Symfony2 database with the help of Select2 and Ajax

Currently, my FAQ System is running smoothly. However, I am looking to enhance it by adding a search function using Select2. Here's what I have so far: Select2 AJAX Script <script> $("#searchall").select2({ ajax: { ...

Utilizing images in a compiler run with the option of `allowJS:true` is key

Looking to develop a React Native library using JavaScript instead of typescript, but want to leverage TSC for its ability to generate type declarations from jsdoc comments. However, encountering an issue where local images are not included when the ts com ...