Skip to content

Instantly share code, notes, and snippets.

@67hz
Created September 15, 2014 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 67hz/fa626bef810d1fe1024b to your computer and use it in GitHub Desktop.
Save 67hz/fa626bef810d1fe1024b to your computer and use it in GitHub Desktop.
Underscore chaining. This example scans a collection, finds all items that match a condition, then returns a new collection from the matches with custom structure.
var subscribersModel = {
users: [
{
'id': '1asdf',
'activeSubscriptions': ['monthly', 'gold'],
'gender': 'm',
'age': '31',
'username': 'CowboyWayne'
},
{
'id': '2df',
'activeSubscriptions': null,
'gender': 'f',
'age': '22',
'username': 'TanyaT'
},
{
'id': '3fda',
'activeSubscriptions': ['monthly'],
'gender': 'm',
'age': '48',
'username': 'BuckO'
}
]
};
var activeUsers = _.map(_.filter(subscribersModel.users, function(user) {
return user.activeSubscriptions > 0;
}), function(user) {
return {
"id": user.id,
"subscriptions": user.activeSubscriptions
};
});
console.log(activeUsers);
// logs:
// [
// {
// id: '1asdf',
// subscriptions: ['monthly', 'gold']
// },
// {
// id: '3fda',
// ['monthly']
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment