0

Novice in node.js here. I am using csvtojson to read a csv into an object fileDataObject, like that:

    const csv=require("csvtojson");
    csv(
        {
            delimiter:mq.delim
            ,trim:false
        }
    )
    .fromFile(mq.folder_pending+'\\'+file)
    .then((fileDataObject)=>{

What I'd like is for fileDataObject to have an additional "column" (property) named row_number, which indicates the source line number of the file.

The documentation mentions something about a file line hook, but I don't know how to use hooks.

George Menoutis
  • 6,894
  • 3
  • 19
  • 43

1 Answers1

1

There is already an example on the package readme.

Once you get your fileDataObject (in your example), you can simply add a column key

For example

  const csv=require('csvtojson')
csv()
.subscribe((jsonObj,index)=>{
    jsonObj.myNewKey='some value'
    // OR asynchronously
    return new Promise((resolve,reject)=>{
        jsonObj.myNewKey='some value'; <-- add column here
        resolve();
    })
})
.on('data',(jsonObj)=>{
    console.log(jsonObj.myNewKey) // some value
});

For your example

const csv=require("csvtojson");
csv(
    {
        delimiter:mq.delim
        ,trim:false
    }
)
.fromFile(mq.folder_pending+'\\'+file)
.then((fileDataObject)=>{
     //if you already have a javascript object, u can manually do it too.
     let counter = 1;
     const fileDatWithRowNumber = fileDataObject.map( item => {
          item.row_number = counter;
          counter++; 
          return item
     })
     return fileDatWithRowNumber
}
Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • So, the idea is that the row number is the same as the `fileDataObject` array index, right? But can I be sure about that? Could it be that the array might be stored in a mixed order? – George Menoutis May 24 '21 at 07:15
  • it's the index+1 since index starts from 0. The index will be according to the line number in the file. I don't think there's any reason it may be stored in a mixed order unless you mutate it. – Someone Special May 24 '21 at 07:17