CSVParse for Node.js

IssuesGitHub

Option objname

The objname option associates records using one of the fields as keys.

With the columns option, the field is identified by its column name. It must be a string or a buffer. Without the column option, the field is identified by its index position. It must be a number.

The option is compatible with the raw and info options.

As a column name

Field names reference one of the record property. Thus, they require the usage of the column option to generate records as object literal instead of array.

Below, the objname option is a string and it defines the c1 column:

import assert from 'assert';
import { parse } from 'csv-parse/sync';

const records = parse('c1,c2,c3\na,b,c\nd,e,f', {
  columns: true,
  objname: 'c2'
});

assert.deepStrictEqual(records, {
  b: { c1: 'a', c2: 'b', c3: 'c' },
  e: { c1: 'd', c2: 'e', c3: 'f' } 
});

As an index name

Index names reference a record field by its position. Thus, records must be generated as arrays.

Below, the objname option is a number and it defined the field in the second postion at index 1:

import assert from 'assert';
import { parse } from 'csv-parse/sync';

const records = parse('a,b,c\nd,e,f', {
  objname: 1
});

assert.deepStrictEqual(records, {
  b: ['a', 'b', 'c'],
  e: ['d', 'e', 'f']
});