How to get Papa.parse results into an array
Asked Answered
I

2

4

Forewarning, I am new to js and I crafted the code below was taken from Retrieve parsed data from CSV in Javascript object (using Papa Parse)

my goal = parse a csv file into an array, and use that array in a few other operations. I can see that the file is getting parsed properly via the "console.log("Row:", row.data);", but I cannot figure out how to get that entire array/dataset into a separate variable, much less into the "doSAtuff" function.

function parseData(url, callBack) {
  Papa.parse(url, {
        download: true,
        header: true,
        dynamicTyping: true,
        comments: "*=",
        step: function(row) {
            console.log("Row:", row.data);
        },
        complete: function(results) {
          callBack(results.data);
        }
    });
}

function doStuff(data) {
    //Data should be usable here, but is emtp
    console.log("doStuff - console log '" + data + "' ?");
}

parseData(inputFile, doStuff);

I think I want to do something like...

var csvArray = [];

csvArray = Papa.parse(url, {
        download: true,
        header: true,
        dynamicTyping: true,
        comments: "*
...

<some other stuff with csvArray>

but i'm a bit wrapped around the axle at the moment.

Imbroglio answered 24/6, 2018 at 19:15 Comment(0)
H
2

I know that if you remove the header: true setting then Papa.parse will return you an Array instead of an Object.

Alternatively you could just convert the object that is returning into an array using something like:

function _arrayify(obj) { return Object.keys(obj).map(function (k) { return obj[k]; }) }
Hadlee answered 4/7, 2018 at 9:41 Comment(0)
I
1

const url = "https://www.papaparse.com/resources/files/normal.csv";

let results;

const csvData = Papa.parse(url, {
      dynamicTyping: true,
      download: true,
      header: true,
      comments: "*=",
      complete: function(data) {
        results = data.data
      }
});

setTimeout(()=> {
  console.log(results[0].ISSN)
}, 1500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.5.0/papaparse.min.js">
</script>
Institutive answered 6/7, 2018 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.