juanjoDiaz / json2csv

Flexible conversion between JSON and CSV
https://juanjodiaz.github.io/json2csv/
MIT License
296 stars 32 forks source link

Error in .ts file while using transforms #26

Closed lupeaserban closed 1 year ago

lupeaserban commented 1 year ago
  1. Include the version of json2csv used and the interface that you are using (plainjs, node or whatwg). Using "@json2csv/node": "^6.1.3"
  2. Include your node version or your browser vendor and version. Node 16

I have my transform function like so:

      function intToString(item) {
        return {
          intVariable: item.intVariable.toString(),
          ...item,
        };
      }

then i have my transforms array and parser next:

const Opts = {
     fields: [ {},  {} ],         // i have some selection enabled here that works fine
     transforms: [ intToString() ]
}

const asyncParser = new AsyncParser(opts);

The file is .ts and the error says:

Expected 1 arguments, but got 0.ts(2554)
index.ts(42, 28): An argument for 'item' was not provided.
(local function) intToString(item: any): any

I also tried with a closure to clear the error and adapted my function to this:

function intToString() {
  return (item) => ({
    intVariable: item.intVariable.toString(),
    ...item,
  });
}

However the transformation isn't happening.

Any help or lead is appreciated. Thanks.

juanjoDiaz commented 1 year ago

Hi,

Sorry for the delay responding.

      function intToString(item) {
        return {
          intVariable: item.intVariable.toString(),
          ...item,
        };
      }

will just return the item as it is. You probably want:

      function intToString(item) {
        return {
          ...item,
          intVariable: item.intVariable.toString(),
        };
      }

so the intVariable field is set to the string.

Also, you are not passing the transform. You are executing it.

const Opts = {
     fields: [ {},  {} ],         // i have some selection enabled here that works fine
     transforms: [ intToString ]  // without the parentheses
}

If you wan to use the parentheses you just need to use the closure. The reason it didn't show up before is because what I said before about your transform beign wrong 🙂