dev.pus
dev.pus

Reputation: 8139

Find object in an array

I want to implement some sort of hasObject function with underscore.js.

Example:

var Collection = {
    this.items: [];
    this.hasItem: function(item) {
        return _.find(this.items, function(existingItem) { //returns undefined
            return item % item.name == existingItem.name;
        });
    }
};

Collection.items.push({ name: "dev.pus", account: "stackoverflow" });
Collection.items.push({ name: "margarett", account: "facebook" });
Collection.items.push({ name: "george", account: "google" });

Collection.hasItem({ name: "dev.pus", account: "stackoverflow" }); // I know that the name would already be enough...

For some reason underscores find returns undefined...

What am I doing wrong?

Upvotes: 0

Views: 514

Answers (2)

James Florentino
James Florentino

Reputation: 76

You need to check both values for the name and the account.

var Collection = {
  this.items: [];
  this.hasItem: function(target) {
    return _.find(this.items, function(item) {
      return item.name === target.name && item.acount === target.account;
    });
  }
};

Have you considered using Backbone.js? It fulfills all your collection management needs and uses underscore's methods too.

// create a collection
var accounts = new Backbone.Collection();

// add models
accounts.add({name: 'dev.pus', account: 'stackoverflow'});
accounts.add({name: 'margarett', account: 'facebook'});
accounts.add({name: 'george', account: 'google'});

// getting an array.
var results = accounts.where({ name: 'dev.pus', account: 'stackoverflow' });

Upvotes: 0

Esailija
Esailija

Reputation: 140220

It looks like you are reading underscore documentation too literally, where they have:

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

However, this doesn't make any sense for your case, you just want to see if the .name property is equal to some other object's .name, like this:

var Collection = {
    items: [],

    hasItem: function(item) {
        return _.find(this.items, function(existingItem) { //returns undefined
            return item.name === existingItem.name;
        });
    }
};

Upvotes: 4

Related Questions