<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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.