Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created September 14, 2016 09:50
Show Gist options
  • Save loretoparisi/4f2cf54b8ea86aee2008599d1926e1e3 to your computer and use it in GitHub Desktop.
Save loretoparisi/4f2cf54b8ea86aee2008599d1926e1e3 to your computer and use it in GitHub Desktop.
JavaScript map and filter object extensions
/********************
* Object modifiers
********************/
/**
* Object.mapObject(value,key)
* Map Object properties
* @return object Copy of this object
*/
if( typeof( Object.mapObject ) == 'undefined') {
Object.defineProperty(Object.prototype, 'mapObject', {
value: function(f, ctx) {
ctx = ctx || this;
var self = this, result = {};
Object.keys(self).forEach(function(k) {
result[k] = f.call(ctx, self[k], k, self);
});
return result;
}
});
}
/**
* Object.filterObject(value,key)
* Filter object properties
* @return object This object modified
*/
if( typeof( Object.filterObject ) == 'undefined') {
Object.defineProperty(Object.prototype, 'filterObject', {
value: function(f, ctx) {
ctx = ctx || this;
var self = this, result = {};
Object.keys(self).filter(v => { return ( !f.call(ctx, self[v], v, self) ) }).forEach(v => { delete self[v]; } )
}
});
}
@loretoparisi
Copy link
Author

Usage:

var zoo = {
 animals : 100,
 zookeeper : 3,
 kinds : ["tiger", "elephant", "lion"]
}

aquarium=zoo.mapObject((v,k) => { if( k=='kinds') v.push('platypus'); return this[k]=v })
console.log(aquarium)

aquarium.filterObject((v,k) => { return k=='kinds' })
console.log(aquarium)

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