-4

I have a react project with nodejs mongodb and I use csvparser to transform data from a csv table into data in my database, I noticed that the first key of my table is necessarily between coast for example :

fs.createReadStream(filePath)
    .pipe(csv({ separator: ';' })) 
    .on('data', (data) => {
      console.log(data)

Here's the answer :

{
  'Bookmaker': 'Unibet',
  Tipster: '',
  Sport: 'Football',
  Categorie: '',
  Competition: '',
  Type_de_pari: '',
  Pari_gratuit: '',
  Live: '',
  Type: 'Simple',
  Intitule_du_pari: 'Montpellier - Lille : Plus de 1,5 buts',
  Cote: '1.35',
  Mise: '50',
  Gain: '-50',
  Bonus_de_gain: '',
  Commission: '',
  Benefice: '-50',
  Etat: 'Perdu',
  Closing_Odds: '',
  Commentaire: ''
}

And from then on I can't access the bookmaker value because neither console.log(data.Bookmaker) nor console.log(data.['Bookmaker'] work. How can I retrieve the bookmaker values?

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    `data["'Bookmaker'"]`…? Are the quotes simply part of the string, because that's how it's written in the CSV…? Alternative guess: there are some invisible characters in that string, because your CSV starts with, maybe a BOM? – deceze Jul 24 '23 at 12:34

1 Answers1

0

It looks like the data object you are getting from the csv-parser is using the first row as the header, and the keys of the object are defined based on the values in the first row. However, the keys seem to have leading or trailing spaces in their names, which is causing the issue when accessing them using dot notation.

To access the 'Bookmaker' value, you should use bracket notation, but you need to make sure to use the correct key name, considering the potential leading or trailing spaces. Here's how you can do it:

const dataRows = [];

fs.createReadStream(filePath)
  .pipe(csv({ separator: ';' })) 
  .on('data', (data) => {
    dataRows.push(data);
  })
  .on('end', () => {
    const sanitizedKeys = Object.keys(dataRows[0]).map((key) => key.trim());
    const bookmakerKey = sanitizedKeys.find((key) => key === 'Bookmaker');

    if (bookmakerKey) {
      dataRows.forEach((data) => {
        console.log(data[bookmakerKey]);
      });
    }
  });

By sanitizing the keys and then finding the correct key name, you can access the 'Bookmaker' value using bracket notation without any issues.

Basir khan
  • 168
  • 8
  • I tried your solution but unfortunately the : `if (bookmakerKey) { console.log(data[bookmakerKey]); }` returns 'undefined' as if there were no value, even though there is a value. If I console.log(bookmakerKey) it gives me the name of my key (Bookmaker), so it can find it, but it can't give me its value (Unibet). – Lucas Barray Jul 24 '23 at 13:04
  • try the updated solution – Basir khan Jul 24 '23 at 15:54
  • I tried the new version of the code but it still console.log undefined nothing to do. – Lucas Barray Jul 24 '23 at 16:13