我想做一些类似 sql groupBy 的事情,但在 jQueryeach 中。
我的代码:
$.each(allItems, function (i, val) {
var itemIconURL = val['itemIcon'];
var itemIcon = 'http://steamcommunity-a.akamaihd.net/economy/image/' + itemIconURL + '/90fx90f';
str += '<img src="'+ itemIcon +'"/>';
console.log('key:' +i+ ', value:' + itemIconURL +'');
});
我想做:
如果这个相同的值只显示其中之一并获取分组的数量。
它需要按itemIconURL
分组。
最佳答案
使用 counters
哈希来计算 itemIconURL
s 随着循环的进行,并且只创建 <img>
每个 itemIconURL
第一次出现时的 HTML .
var counters = {},
str = '';
$.each(allItems, function (i, val) {
var itemIconURL = val['itemIcon'];
if(!counters[itemIconURL]) {
counters[itemIconURL] = 1;
var itemIcon = 'http://steamcommunity-a.akamaihd.net/economy/image/' + itemIconURL + '/90fx90f';
str += '<img src="' + itemIcon + '"/>';
console.log('key:' + i + ', value:' + itemIconURL + '');
} else {
counters[itemIconURL] += 1;
}
});
console.log(counters);
// Now do whatever is necessary with the `counters` hash,
// for example, loop through it
$.each(counters, function(key, value) {
// do something with `key` and/or `value`
});
编辑
从字里行间看出,我希望你想要这样的东西:
var counters = {},
str = '';
// First tally up the group counts
$.each(allItems, function (i, val) {
var itemIconURL = val['itemIcon'];
if(!counters[itemIconURL]) {
counters[itemIconURL] = 1;
} else {
counters[itemIconURL] += 1;
}
});
// Now build the HTML
$.each(counters, function(key, value) {
var itemIcon = 'http://steamcommunity-a.akamaihd.net/economy/image/' + key + '/90fx90f';
str += '<img src="' + itemIcon + '"/>' + value;
});
$("#someContainer").html(str);
关于jquery - 为每个 jQuery 分组相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35101175/