Skip to main content

JSON2CSV

Converts an array of JSON objects into CSV. Provides custom mapping of column names and merging of column values (resolves to first found in priority order), as well as custom delimiter and column/row/key joiners. Context attributes can be added to all rows and column-specific value replacements may be defined.

import { tools } from 'tods-competition-factory';

const config = {
includeTransformAccessors, // optional boolean - transform accessors are included with columnAccessors
removeEmptyColumns, // optional boolean - remove columns which contain no values
columnAccessors, // optional - array of column accessors to include [ 'includeThis', 'andThis' ]
columnTransform, // optional - multiple generated column names can resolve to a single custom column, e.g. { 'newColumnName': ['oldColumn1', 'oldColumn2' ]}
columnMap, // optional - simple mapping from generated columnName to custom columnName, e.g. { 'columnName': 'newColumnName' }
functionMap, // optional - transform values, e.g. { 'columnName': (value) => value }
valuesMap, // optional - map values for specified columns, e.g. { 'columnName': { 'value': 'mappedValue '}}
sortOrder // optional - e.g. ['columnName1', 'columnName2'] // determine order of csv columns
context, // optional - object defining values which should be added to all rows, e.g. { 'columnName': 'columnValue '}
delimiter, // optional - defaults to '"'
columnJoiner, // optional - defines how CSV columns are joined; defaults to ','
rowJoiner, // optional - defines how CSV lines are joined; defaults to '\r\n'
keyJoiner, // optional - defines how flattened column names are constructed; defaults to '.'
};
const arrayOfJSON = [{ a: 1 }, { b: 2 }];
const csv = tools.JSON2CSV(arrayOfJSON, config);
note

columnTransform mapped array elements are sensitive to order and will resolve to the first matching value

columnMap should not contain new columnName(s) that are columnTransform keys

Example converting matchUps

In the following example SINGLES and DOUBLES draws are generated and all matchUps are completed. The config object defines how participants for each side of each matchUp are to be extracted, prioritizing the accessor for extracting { participantType: PAIR }, and falling back on the accessor for participantName.

Live Editor
Result
Loading...