Skip to content

Instantly share code, notes, and snippets.

@select select/objectsToCsv.js
Last active Nov 12, 2018

Embed
What would you like to do?
Convert an Array of non uniform Objects to a CSV string with JavaScript
function getKeys(obj, prefix = '') {
if (typeof obj === 'undefined' || obj === null) return [];
return [
...Object.keys(obj).map(key => `${prefix}${key}`),
...Object.entries(obj).reduce((acc, [key, value]) => {
if (typeof value === 'object') return [...acc, ...getKeys(value, `${prefix}${key}.`)];
return acc;
}, []),
];
}
function flatObject(obj, prefix = '') {
if (typeof obj === 'undefined' || obj === null) return {};
return Object.entries(obj).reduce((acc, [key, value]) => {
if (typeof value === 'object') return { ...acc, ...flatObject(value, `${prefix}${key}.`) };
return { ...acc, [`${prefix}${key}`]: value };
}, {});
}
function escapeCsvValue(cell) {
if (cell.replace(/ /g, '').match(/[\s,"]/)) {
return '"' + cell.replace(/"/g, '""') + '"';
}
return cell;
}
function objectsToCsv(arrayOfObjects) {
// collect all available keys
const keys = new Set(arrayOfObjects.reduce((acc, item) => [...acc, ...getKeys(item)], []));
// for each object create all keys
const values = arrayOfObjects.map(item => {
const fo = flatObject(item);
const val = Array.from(keys).map((key: string) => (key in fo ? escapeCsvValue(`${fo[key]}`) : ''));
return val.join(',');
});
return `${Array.from(keys).join(',')}\n${values.join('\n')}`;
}
@garygrubb

This comment has been minimized.

Copy link

garygrubb commented Nov 12, 2018

Wonderful. Thanks for the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.