gpt4 book ai didi

javascript - 使用 Meteor 对集合中的对象进行分组

转载 作者:行者123 更新时间:2023-12-02 16:01:09 26 4
gpt4 key购买 nike

我有一个包含字段typenumber的集合。

现在我正在打印集合中的文档

{{#each myRows}}
<tr>
<td>{{type}}</td>
<td>{{number}}</td>
</tr>
{{/each}}

许多行具有相同的type值,因此我想按type对行进行“分组”。我怎样才能获得这个?我需要类似的东西

{{#types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbersInType}}
<tr>
<td>{{type}}</th>
</tr>
{{/each}}
{{/each}}

最佳答案

尝试一下这样的事情:

Template.myTemplate.helpers({
types: function() {
// fetch your rows somehow
var rows = Collection.find().fetch();

// hash of type data
var types = {};

_.each(rows, function(row) {
var type = row.type

// initialize each type in the hash if it isn't defined
if (types[type] == null)
types[type] = {type: type, numbers: []};

// add the numbers to the array for this type
types[type].numbers.push(row.number);
});

// the values of the has contain an array of properly formed data
return _.values(types);
}
});

助手的结果将如下所示:

[ { type: 'a', numbers: [ 1, 2, 3 ] },
{ type: 'b', numbers: [ 10, 11, 12 ] },
{ type: 'c', numbers: [ 100 ] } ]

这是一个示例模板片段:

{{#each types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbers}}
<tr>
<td>{{this}}</th>
</tr>
{{/each}}
{{/each}}

关于javascript - 使用 Meteor 对集合中的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com