簡體   English   中英

從對象列表中獲取屬性

[英]take an attribute from a list of objects

通過使用underscorejQuery我需要將maximum id值增加一個包含在對象列表中的值。

javascript對象是Backbone.Collection ,它看起來像這樣:

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

我編寫了以下有效的代碼,但我想知道是否有任何更改可以改進它。

謝謝。

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

_.max接受回調迭代器函數:

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

我知道lodash庫是真的,不知道下划線是真的。

干杯!

一種方法是使用比較器方法按ID對您的集合進行排序。

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

設置時,保證您的最后一個模型具有bigts ID。

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

在定義集合時最好定義這些:

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

現場演示

這個怎么樣:

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

簡單的循環沒有什么問題,在集合內部這樣的事情是完全可以接受的:

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;

如果您被迫使用Underscore,則可以這樣:

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

兩者都將進入集合內部,在集合外部接觸集合的models數組是不好的舉止。

僅僅因為您擁有所有的jQuery和Underscore機制,並不意味着您必須在任何地方使用它。

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

並且不要使用此:

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

這是正確的方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM