misc functions: clean_empty_keys_recursive(), console_log_without_prototypes(), sideBySide() strings

misc functions: clean_empty_keys_recursive() console_log_without_prototypes()

by Laurens Maneschijn

HTML

<pre>
see console

misc functions:

clean_empty_keys_recursive()

console_log_without_prototypes(...args)

sideBySide1(str1, str2)
sideBySide2(strings)
sideBySide3(args, options)

</pre>

JavaScript

// clean empty keys from object recursively.
// long json strings sometimes get truncated in logs.
// try to filter out empty (null, and perhaps "", [], or 0) key: value items so we see more non empty and useful keys in logs.

function clean_empty_keys_recursive(obj, options) {
	if (!typeof obj === 'object') {
		return obj;
	}
	function is_empty_value(value, key, parent, path) {
		return value === undefined
			|| (value === null)
			|| (value === '')
			|| (Array.isArray(value) && value.length === 0)
		;
		// TODO: array with only empty values?
		// TODO: object with only empty values?
		// TODO: object without keys?
	}
	var options_default = {
		is_empty_value: is_empty_value,
		varname: 'obj',
		path: [],
		log: true,
	}
	var o = Object.assign({}, options_default, options || {})
	o.path = Array.isArray(o.path) ? o.path : [];

	for (var key in obj) {
		var newpath = o.path.slice(0).concat([key]);
		if (o.is_empty_value(obj[key], key, obj, newpath)) {
			if (o.log) {
				console.log('deleted: '+o.varname+'["' + newpath.join('"]["') + '"] = ', obj[key]);
			}
			delete obj[key];
		} else if (typeof obj[key] === 'object') {
			obj[key] = clean_empty_keys_recursive(obj[key], Object.assign({}, options, {path: newpath}));
		}
	}
	return obj;
}

function console_log_without_prototypes () {
	// source:
	// https://stackoverflow.com/questions/11818091/hiding-the-proto-property-in-chromes-console
	// https://stackoverflow.com/a/30085019/1158769
	// WARNING: not 100% sure it it does not alter original objects.
	function clear_prototype_recursive(obj) {
		obj = JSON.parse(JSON.stringify(obj)); // clone (don't change original objects)
		if (obj && typeof obj === 'object') {
				obj.__proto__ = null;
				for (var j in obj) {
					obj[j] = clear_prototype_recursive(obj[j]);
				}
		}
		return obj;
	}
	for (var i = 0, args = Array.prototype.slice.call(arguments, 0); i < args.length; i++) {
		args[i] = clear_prototype_recursive(args[i]);
	}
	console.log.apply(console,...