0

I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.

(Example of my test file, being the columns A and B respectively):

    Johny Wilson    | jonhny@email.com
    Andrew Jehnsen  | andrew@example.com
    Billy Soon      | billy@mail.com

In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:

    var xlsx = require('node-xlsx');

    router.post('/enviar', upload.single("lista"),(req, res, next) =>{
        //dir is the path of the xlsx file
        const workSheetsFromFile = xlsx.parse(dir); 
        res.send(workSheetsFromFile);
    });

returns an object that looks like this:

    [
        {
            "name": "Hoja1",
            "data": [
                [
                    "Johny Wilson",
                    "jonhny@email.com"
                ],
                [
                    "Andrew Jehnsen",
                    "andrew@example.com"
                ],
                [
                    "Billy Soon",
                    "billy@mail.com"
                ]
            ]
        }
    ]

As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.

I've already tried to loop on the data array with:

    workSheetsFromFile.data.forEach((element) =>{
        console.log(element);
    });

and

    workSheetsFromFile[data].forEach((element) =>{
        console.log(element);
    });

and

    workSheetsFromFile['data'].forEach((element) =>{
        console.log(element);
    });

but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(

For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.

  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Heretic Monkey Jan 06 '19 at 21:00

3 Answers3

4

What you have here seems to be an array of objects, not an object itself!

try

 workSheetsFromFile[0].data.forEach((element) => {
     console.log(element);
 });

If you have more elements, consider first looping the array and then extracting data

fkajzer
  • 179
  • 11
1
const structuredData = workSheetsFromFile[0].data.map(res => {
     return res
});
Joelgullander
  • 1,624
  • 2
  • 20
  • 46
1
workSheetsFromFile.forEach(sheet => {
   //access data
   console.log(sheet.data)

   //or

   sheet.data.forEach(data => {
   //access each data
   console.log(data)
   })
})
Jurshsmith
  • 182
  • 2
  • 4