Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all models in backbone collection where attribute is NOT equal to some value

This is taken from the Backbone.js documentation:

var musketeers = friends.where({job: "Musketeer"});

Where you can get an array of models where job is equal is "Musketeer". But how do I do the opposite? How can I get an array of models where job is anything else but "Musketeer"?

like image 852
Dragonfly Avatar asked Feb 06 '14 16:02

Dragonfly


People also ask

How do I get the value of an attribute in backbone?

Backbone.js model.get() The Backbone.js Get model is used to get the value of an attribute on a model. Syntax: attributes: It defines property of a created model. Let's take an example. See this example: Output: Save the above code in get.html file and open this file in a new browser.

What is collection in backbonejs?

BackboneJS - Collection. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly. This allows you to listen for changes to specific attributes in any model in a collection.

What are the methods of collection in backbone?

All the Backbone.JS Collection’ methods are listed below: To extend the backbone’s collection class to create own collection. To specify the model class. To create a model instance. To specify the array of models which are created inside of the collection.

What is a backbone model?

Here’s a little excerpt from the Backbone docs on models: Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. With that in mind, let’s draft up a little example that we’ll use going forward.


2 Answers

I don't know of something that's a direct opposite, but you can use a filter to the same effect.

var notMusketeers = friends.filter(function (friend) {
  return friend.job !== 'Musketeer';
});
like image 84
reergymerej Avatar answered Oct 15 '22 13:10

reergymerej


If you're using filter directly on a Backbone collection, you must use it this way:

var notMusketeers = friends.filter(function(model){
    return model.get('job') !== 'Musketeer';
});

Then notMusketeers will be an array of Backbone model instances.

If friends is just an array of objects (standard collection), you could use the underscore filter this way:

var notMusketeers = _.filter(friends, function(obj){
    return obj.job !== 'Musketeer';
});

ES6

If ES6+ features are available to you, const, destructuring and arrow functions could make it a little less verbose:

const notMusketeers = friends.filter(({ job }) => job !== 'Musketeer');
like image 36
Emile Bergeron Avatar answered Oct 15 '22 14:10

Emile Bergeron