Last active
August 29, 2015 14:25
-
-
Save Willovent/6a720289ebf0d6d46250 to your computer and use it in GitHub Desktop.
Array select
usage : [{name : "William", age : 24}, {name : "Bertrand", age : 47}].select('age'); => return : [{age : 24}, {age : 47}] parameter can be a string or an Array of prop to select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Array select | |
usage : [{name : "William", age : 24}, {name : "Bertrand", age : 47}].select('age'); | |
=> return : [{age : 24}, {age : 47}] | |
parameter can be a string or an Array of prop to select*/ | |
Array.prototype.select = function(props){ | |
var newArray = []; | |
this.forEach(function(e){ | |
var newObj = {}; | |
if(typeof(props) === "string") | |
props = [props]; | |
props.forEach(function(prop){ | |
if(e[prop] !== undefined) | |
newObj[prop] = e[prop]; | |
}); | |
newArray.push(newObj); | |
}); | |
return newArray; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment