table icon indicating copy to clipboard operation
table copied to clipboard

Suggestion: Utility for Using Flat Objects as a Row

Open CodeMan99 opened this issue 7 years ago • 0 comments

Opening as an Issue because I am not sure where to land the code.

/**
 * Convert a flat object to an array of values suitable for use with [table]{@link https://npmjs.com/package/table}.
 *
 * @param {Object} obj source of plain values
 * @param {Object} [options]
 * @param {string[]} [options.columns] the key names to use. Order is respected. Default is the result of `Object.keys(obj)`
 * @param {Object} [options.custom=null] additional values to use. Keys must not overlap with source obj.
 * @param {*} [options.default=''] value to use if a column name is not found in either the source obj or additional custom values.
 * @returns {Array} values in the same order as the specified columns
 */
function rowify(obj, options) {
	const columns = options && options.columns || Object.keys(obj);
	const custom = options && options.custom;
	const missingValue = options && options['default'] || '';
	const row = [];

	// add keys if no columns were specified
	if (custom && !options.columns) {
		columns.push(...Object.keys(custom));
	}

	for (const column of columns) {
		if (obj.hasOwnProperty(column)) {
			row.push(obj[column]);
		} else if (custom && custom.hasOwnProperty(column)) {
			row.push(custom[column]);
		} else {
			row.push(missingValue);
		}
	}

	return row;
}

Simple Usage

const data = [
    {a: 1, b: 2},
    {a: 3, b: 4}
];

console.log(table(data.map(obj => rowify(obj))));
/*** ouput ***
╔═══╤═══╗
║ 1 │ 2 ║
╟───┼───╢
║ 3 │ 4 ║
╚═══╧═══╝
***/

Advanced Usage

const data = [
    {a: 1, b: 2, c: 3},
    {a: 4, b: 5, c: 6}
];
const rows = data.map(obj => rowify(obj, {
    columns: ['b', 'a', 'd'],
    custom: {
        d: obj.a + obj.c
    }
}));

console.log(table(rows));
/*** output ***
╔═══╤═══╤════╗
║ 2 │ 1 │ 4  ║
╟───┼───┼────╢
║ 5 │ 4 │ 10 ║
╚═══╧═══╧════╝
***/

Let me know if you think others will find this useful :)

CodeMan99 avatar Dec 23 '18 22:12 CodeMan99