searching data in csv file with Javascript

Asked

Viewed 132 times

1

I’m researching a solution to a problem and I haven’t found anything I could understand, so far,

I have a csv file that contains the data in this format:

0111-3/01,"Cultivation of rice"

On the left is the code, and on the right is the description, separated by a comma.

The file has more than 2 thousand lines.

What I need:

The user types the code in the html field, then the function searches the.csv file for that code, and returns the description. It would be something like:

$("#idInputCódigo").focusout(function(){

    //abre arquivo csv que está junto com os arquivos do sistema na pasta _CSV

    arquivo = open(_CSV/arquivo.csv); //função inventada

    for( i = 0; i<quantidade de linhas; i++ ){

        //alguma forma de percorrer o arquivo até encontrar o código correspondente e retornar a descrição
    }

I don’t know if there is any library in javascript that facilitates this, anyway, all help is welcome.

Thank you in advance.

1 answer

1


I managed to solve, I’ll leave the solution here to help someone one day.

I converted my csv file into a json file, has several sites on the net that does it automatically, it was like this:

json:

[
  {
    "code": "0111-3/01",
    "description": "Cultivo de arroz"
  },
  {
    "code": "0111-3/02",
    "description": "Cultivo de milho"
  },
  {
    "code": "0111-3/03",
    "description": "Cultivo de trigo"
  }, .... (mais de 2 mil itens)
    ]

I created a variable in javascript containing json

var cnae = [
             {
              "code": "0111-3/01",
              "description": "Cultivo de arroz"
             }, 
               ....

then created the javascript function that searches the code in the variable, and returns the Description

function CNAE(value){

   var descricao;
   for (var i = 0; i < cnae.length; i++){
      if (cnae[i].code == value){
        descricao = cnae[i].description;
        //aqui acho que o return pode ser direto, sem a variável
        return descricao;
      }
   }

}

Despite the amount of objects in the variable, it works instantaneously, very fast. I hope to help someone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.