为每个jQuery分组相同的值

时间:2016-01-30 11:25:01

标签: jquery key grouping each

我想做sql groupBy 之类的事情,但是 jQuery

我的代码:

$.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分组。

1 个答案:

答案 0 :(得分:1)

在循环进行时使用counters哈希来计算itemIconURL,并且只在每个<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);