在数组中查找对象

时间:2012-07-15 14:11:00

标签: javascript underscore.js

我想用underscore.js实现某种hasObject函数。

示例:

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...

出于某种原因,下划线发现返回未定义...

我做错了什么?

2 个答案:

答案 0 :(得分:4)

看起来你在字面上读取下划线文档,在哪里 他们有:

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

但是,这对您的情况没有任何意义,您只想查看.name属性是否等于 一些其他对象的.name,如下所示:

var Collection = {
    items: [],

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

答案 1 :(得分:0)

您需要检查名称和帐户的两个值。

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

您是否考虑过使用Backbone.js?它满足您的所有集合管理需求,并使用下划线的方法。

// 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' });