【问题标题】:Grouping same value for each jQuery为每个 jQuery 分组相同的值
【发布时间】:2016-01-30 11:25:00
【问题描述】:

我想做类似 sql groupBy 但在 jQuery each 中。

我的代码:

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

【问题讨论】:

    标签: jquery key grouping each


    【解决方案1】:

    随着循环的进行,使用counters 哈希计算itemIconURLs,并且仅在每个itemIconURL 首次出现时创建&lt;img&gt; 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);
    

    【讨论】:

    • 但是计数器不只显示数字,而是整个 URL 和数字,我只需要获取数字
    • 循环完成后您对counters 的处理取决于您。我刚刚写了console.log(counters);,因为我不知道你想对这些数据做什么。
    • 计数器显示例如:1,2,3,4,5,6,7,8。我只想显示最后生成的数字。怎么样?
    • 看看你能不能写一个jsFiddle来证明症状。
    • 我无法想象这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    相关资源
    最近更新 更多