我有一组 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
的 View 。不确定如何为 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;
}
});
希望有人能帮助我。
非常感谢
最佳答案
使用 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>
-查看。
关于javascript - 如何使用 _.each() 对相同值的数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21773257/