Object.prototype.subset

by Laurens Maneschijn

HTML

<pre>
Object.prototype.subset = function(keys){}
function to return only part of an object, and possibly also only parts of subobjects.
see javascript for details and examples.
</pre>

JavaScript

/**
 * subset() : return subselection of this object,
 * and possibly also subselection of childobjects.
 *
 * if keys === true,
 *   return this object. (usefull to get entire object of a subobject, and keep prototype chain intact.)
 * if keys === false,
 *   return a copy of this object with all its (hasOwnProperty) keys.
 * if keys is a single string (or number),
 *   return a copy of this object with only the key of the given value.
 * if keys is an array, 
 *   return a copy of this object with only the keys given in the array (array values must be string or number).
 * if keys is an object, 
 *   return a copy of this object with only the keys that are present in the given object, 
 *   and for each object key->value it recursively calls this function with that value on this[key], 
 *     (i.e. : returnobj[key] = this[key]->subset(value) )
 *   unless this[key] is not a value, then it will return whatever is in this[key]
 *     (i.e. : returnobj[key] = this[key] )
 * else return an empty object.
 *
 * (copy of object: a new object with keys copied from original object)
 *
 * @param {*} keys
 * @return {object}
 */
Object.prototype.subset = function(keys){
	// NB: this[k] does not work, but that[k] does. (not sure why)
	var that = this; 
	var o = {};
	if(keys === true){
		// return everything:
		// NB: if this happens to be an Array then it will return an array instead of an object
		// (although technically an Array is still an object)
		return that;
	}else if(keys === false){
		for(var k in that){
			if(that.hasOwnProperty(k)){
				o[k] = that[k];
			}
		}
	}else if(typeof keys === 'string' || typeof keys === 'number'){
		o[keys] = that[keys];
	}else if(Array.isArray(keys)){
		// only works for array with valid object keys as values:
		keys.forEach(function(k){
			if(typeof k === 'string' || typeof k === 'number'){
				o[k] = that[k];
			}
		});
	}else if(typeof keys === 'object'){
		if(keys.hasOwnProperty('*')){
			// allow getting all keys using * , and...