如何在将 Json 转换为 CSV 时在 json2csv 库中提供自定义字段

Vik*_*kas 0 csv node.js express

我正在使用json2csv库将 Json 转换为 CSV,并且通过这样做我成功了

status = Utils.getKey(InvoiceStatus, invoice.status);
        if (InvoiceStatus.isOverDue(invoice.status, invoice.dueDate))
          status = 'overdue';
     const fields = [
              'id',
              // 'invoicePrefix + ' - ' + invoiceNo',
              'invoiceDate',
              'dueDate',
              'customerId',
              'customerName',
              {
                label: 'status',
                value: status,

              },
              // 'status',
              'itemDesc',
              'invoiceAmount',
              'dueAmount'
            ];
            const opts = { fields };
            try {
              const parser = new Json2csvParser(opts);
              const csv = parser.parse(invoices);
              res.send(csv);
            } catch (err) {
              console.error(err);
            }
          }
Run Code Online (Sandbox Code Playgroud)

但是问题出现在这里我想组合两列 'invoicePrefix + ' - ' + invoiceNo'并显示它,但我不知道如何去做,还有一件事,因为你可以在字段变量中看到这一行

{
    label: 'status',
    value: status,

 },
Run Code Online (Sandbox Code Playgroud)

如您所见,status 是存储在变量中的一些值,我给出了 value 键的变量状态,但它没有以 CSV 格式显示变量值,所以有什么方法可以解决这个问题,以便它也打印该变量值。

Mig*_*rón 6

使用正确的语法:

const fields = [
  'id',
  // We set the header label and we provide a function to fill each cell with row data
  {
    label: invoicePrefix + ' - ' + invoiceNo,
    value: (row, field) => row.invoicePrefix + ' - ' + row.invoiceNo
  },
  'invoiceDate',
  'dueDate',
  'customerId',
  'customerName',
  // We set the header label and we provide a function to fill each cell with row data, in this case the same for all rows
  {
    label: 'status',
    value: () => status,
  },
  // 'status',
  'itemDesc',
  'invoiceAmount',
  'dueAmount'
];
Run Code Online (Sandbox Code Playgroud)