简体   繁体   English

从对象列表中获取属性

[英]take an attribute from a list of objects

By using underscore or jQuery I need to take the maximum id value incremented by one contained in a list of objects. 通过使用underscorejQuery我需要将maximum id值增加一个包含在对象列表中的值。

The javascript object is a Backbone.Collection and it looks like this: javascript对象是Backbone.Collection ,它看起来像这样:

this.collection.models = [{attributes: {id: 1, ....}}, {}];

I wrote the following code which works, but I would like to know if there are any change to improve it. 我编写了以下有效的代码,但我想知道是否有任何更改可以改进它。

Thanks. 谢谢。

getId: function () {
  return _.max(
          _.map(
           _.pluck(this.collection.models, 'attributes'), function (attributes) {
              return attributes.id;
    })) + 1;
},

_.max accepts an callback iterator function: _.max接受回调迭代器函数:

var next = _.max(list, function(i) { return i.attributes.id; }).attributes.id + 1;

I knew it was true for the lodash library, didn't know it was true for underscore. 我知道lodash库是真的,不知道下划线是真的。

Cheers! 干杯!

One way is to soert your collection by id, using the comparator method. 一种方法是使用比较器方法按ID对您的集合进行排序。

collection.comparator = function(model) {
    return model.id;
}

When you set that, your last model is guaranteed to have the largets id. 设置时,保证您的最后一个模型具有bigts ID。

collection.next = function(){
    return this.last().id + 1;
}

It would probably better to define these when defining the collection: 在定义集合时最好定义这些:

var Collection = Backbone.Collection.extend({
  comparator: function(model) {
    return model.id;
  },
  next: function(){
    return this.last().id + 1;
  }
});

Live demo here 现场演示

How about this: 这个怎么样:

var result = _.chain(this.collection.models)
    .pluck('attributes')
    .max(function(value) {
        return value.id;
    })
    .value();

There's nothing wrong with simple loops, something like this inside the collection is perfectly acceptable: 简单的循环没有什么问题,在集合内部这样的事情是完全可以接受的:

var max = 0;
for(var i = 0; i < this.models.length; ++i)
    max = this.models[i].id > max ? this.models[i].id : max;
return max + 1;

Or like this if you're compelled to use Underscore: 如果您被迫使用Underscore,则可以这样:

var max = 0;
this.each(function(m) {
    max = m.id > max ? m.id : max;
});
return max + 1;

Both of those would go inside the collection, touching a collection's models array outside the collection is bad manners. 两者都将进入集合内部,在集合外部接触集合的models数组是不好的举止。

Just because you have all the jQuery and Underscore machinery kicking around doesn't mean that you have to use it everywhere. 仅仅因为您拥有所有的jQuery和Underscore机制,并不意味着您必须在任何地方使用它。

var max = _.max(this.collection.pluck('id')) + 1;

And don't use this: 并且不要使用此:

this.collection.models = [{attributes: {id: 1, ....}}, {}];

Here is proper way: 这是正确的方法:

this.collection.reset([{id: 1}, {id: 2}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM