columns
specified.Array.prototype.join(delimiter)
to combine all the names in columns
to create the first row.Array.prototype.map()
and Array.prototype.reduce()
to create a row for each object. Substitute non-existent values with empty strings and only mapping values in columns
.Array.prototype.join('\n')
to combine all rows into a string.delimiter
, to use a default delimiter of ','
.const JSONtoCSV = (arr, columns, delimiter = ',') => [ columns.join(delimiter), ...arr.map(obj => columns.reduce( (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, '' ) ), ].join('\n');
JSONtoCSV( [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'] ); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"' JSONtoCSV( [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';' ); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️