Created
September 15, 2014 20:12
-
-
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.
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
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