Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
Reading CSV in Typescript gives NaN when reading number

Well, I' trying to read a CSV file with Typescript

This is my code:

export default class Playlist{
    public playlistId: Number = 0;
    public playlistName: string = '';

    constructor(line:string){
        const item = line.split(',')
        this.playlistId = +item[0];
        this.playlistName = item[1];
    }
}

fs.readFile('.\\csv\\playlist.csv', 'utf8',(err, res) => {
        if(err){
            console.error('YEET');

            return;
        }else{

            const playlists =  res.split('\n').slice(1).map((x:string) => new Playlist(x))
            console.log(playlists)
        }
    })

This is the CSV data:

"1","Music"
"2","Movies"
"3","TV Shows"
"4","Audiobooks"

This is the Playlist Object I get:

Playlist { playlistId: NaN, playlistName: '"Music"\r' },

As you can see for the playlistId I get NaN but I have no idea why because I parse it to a number correctly. Furthermore, not to neccessary the Name of the Playlist is in a weird format too.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It's because you have speech marks wrapped around each value. Either fix the Playlist class with the following:

Fixed Playlist Class

export default class Playlist {
  public playlistId: Number = 0;
  public playlistName: string = "";

  constructor(line: string) {
    const item = line.split(/"|\\r/).join("").split(",");
    this.playlistId = Number(item[0]); // or keep as =+ item[0]
    this.playlistName = item[1];
  }
}

Or, remove the quotes from the CSV file.

Fixed Playlist CSV

1,Music
2,Movies
3,TV Shows
4,Audiobooks
about 4 years ago · Juan Pablo Isaza Report

0

If you see that your playlistName, it includes an extra pair of double quotes '"Music"\r'.

Before you parse item[0], it should also look like '"1"' and +'"2"' is expected to be NaN when you parse that.

An easy fix would be to just replace all the quotes with empty character, effectively changing the parsing to +item[0].replace(/\"/g, "")

about 4 years ago · Juan Pablo Isaza Report

0

do you not put ; after each value? It's just a question?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!