如何使用_.each()对相同值的数据进行分组

时间:2014-02-14 07:28:00

标签: javascript underscore.js

我有一套JSON,

[{"gp_id":"1","gp_name":"ADMIN","gp_location":"Headquater"},{"gp_id":"2","gp_name":"OE.TT","gp_location":"Timah Tasoh"},{"gp_id":"3","gp_name":"OP.TT","gp_location":"Timah Tasoh"},{"gp_id":"4","gp_name":"USER.HQ","gp_location":"Headquater"}]

如您所见,索引“ gp_location ”中有一些重复值。如何使用_.each(underscoreJs)

实现这样的结果
<select>
 <optgroup label="Headquater">
   <option>ADMIN</option>
   <option>USER.HQ</option>
 </optgroup>
 <optgroup label="Timah Tasoh">
   <option>OP.TT</option>
   <option>OE.TT</option>
 </optgroup>
</select>

到目前为止我所取得的成就是

    render: function() {
        this.$el.empty();
        var container = document.createDocumentFragment(),
            modelgroups = _.groupBy(this.collection.models, "gp_location");         
        _.each(modelgroups, function(group, n) {            
            var optgroup = document.createElement('optgroup');              
            optgroup.label = n;             
            _.each(group, function(base) {                  
                optgroup.appendChild(new BaseListItemView({model: base}).render().el)
            });             
            container.appendChild(optgroup);                
        }); 
        this.$el.append(container);
        return this;
    }

我正在开发一个backboneJS应用程序。如您所见, BaseListItemView 是html元素option的视图。我不确定如何为optgroup

制作另一个视图

更新:此处是BaseListItemView

的代码
 return Backbone.View.extend({
        tagName: "option",

    initialize: function () {               
        this.listenTo(this.model, 'change', this.render);
    },

    render: function () {
        this.$el.html(this.model.attributes.gp_name + ', ' + this.model.attributes.gp_location);
        this.$el.attr( "value" , this.model.attributes.gp_id )
        return this;
    }

});

希望有人可以帮助我。

非常感谢

2 个答案:

答案 0 :(得分:2)

像这样使用groupBy function

var modelgroups = _.groupBy(this.collection.models, "gp_location");

以便您可以使用

进行迭代
_.each(modelgroups, function(group, name) {
    var $group = $("<optgroup>", {label:name});
    _.each(group, function(base) {             
        $group.append(new BaseListItemView({model: base}).render().el)
    });
    this.$el.append($group);
});

您可以从gp_location - 视图中删除<option>

答案 1 :(得分:0)

感谢您的回答@bergi

不确定出了什么问题,但这里的答案略有变化

modelgroups = _.groupBy(this.collection.models, function(model){
    return model.get('gp_location')
    });