Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Utility for Using Flat Objects as a Row #85

Open
CodeMan99 opened this issue Dec 23, 2018 · 0 comments
Open

Suggestion: Utility for Using Flat Objects as a Row #85

CodeMan99 opened this issue Dec 23, 2018 · 0 comments

Comments

@CodeMan99
Copy link

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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants