Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda