Filtering on IDs in JavaScript
In Backbone, you are often working with a collection of models that have their own ID. However, you might run in to a scenario where you only need models from the collection that have a certain property or ID. I do this a lot at my job when it comes to filtering out users that have set a preference to make all their data private.
Here is how we have been doing it with Underscore.js and it has been working out quite nicely:
// Specific data to this example
// Assume users is some backbone collection you have
var users_with_private_data = [{id: 1}, {id: 5}];
var private_user_ids = _.pluck(users_with_private_data, "id");
var filtered_users = _.filter(users.toJSON(), function(user) {
return _.indexOf(private_user_ids, user.id) === -1
});
// Do something with the filtered users....Written by Bryan Mikaelian
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#