使用jQuery从JSON数组中获取唯一结果

12

我有这段代码,它从我的数组中将“类别”显示为JQuery简单列表。

它的表现很好,但如果来自“篮球”类别的项目有3个,则该类别将出现3次。

如何使它们只出现一次?谢谢。

以下是代码:

function loadCategories() {
    console.debug('About to refresh with sort type : ' + sortType);
    var items = [];

    $.each(catalog.products,
        function(index, value) {
            items.push('<li id="' + index + '">' +
                  '<a data-identity="productId"  href="./productList.page?category=' + value.category + '" >' +
                  '<p style="margin-bottom:0px;margin-top:0px;">' + value.category + '</p></a> </li>');
        }
    );

    categoryView.html(items.join(''));
    categoryView.listview('refresh');
}

以下是我的数组代码:

var catalog = {"products": [
{"id": "10001",
"name": "Mountain bike",   
"color": "Grey/Black",
"long-desc": "12-speed, carbon mountain bike.",
"description": "",
"size": "20 inches",
"category": "Outdoors/ Equipment rental",
"sport": "Cycling",
"brand": "DaVinci",
"top-seller": ""},

{"id": "10002",
"name": "Pro Multi Basketball",   
"color": "Rainbow",
"long-desc": "On sale this week only! This limited edition basketball is multi-coloured, and offers pro performance. Fun and games on the court!",
"description": "Limited edition basketball.",
"size": "N/A",
"category": "Team gear",
"sport": "Basketball",
"brand": "Nike",
"top-seller": "x"},
3个回答

24

我不知道你的products数组是如何构建的(因此我的示例可能需要根据你的需求进行一些修改),但你可以编写一小段代码,将首先收集你的唯一类别到一个新数组中:

var categories = [];

$.each(catalog.products, function(index, value) {
    if ($.inArray(value.category, categories) === -1) {
        categories.push(value.category);
    }
});

jsFiddle演示

categories 将保存你所需的唯一类别,你可以使用它来构建你的HTML(但要小心那些

  • 元素的ID,记住ID不能重复,你可能会给它们一个小前缀)。


  • 似乎不起作用.. 我会继续通知你。如果你有时间,我已经编辑了我的问题,并附上了我的数组代码。再次感谢。 - JFFF
    @JFFF 我已经将你的示例对象加载到我的代码中:jsFiddle Demo #2。对我来说似乎可以工作。请随意调整我的小提琴以获得您期望的结果(也许您想将其他值添加到“categories”数组中)。 - kapa
    你好,有没有办法使其对于任何其他字段都是唯一的,比如(使用类别JSON)你想要所有颜色而没有重复的。 - Djeroen
    @Djeroen 是的,有的,你只需要稍微改一下代码就可以了。我建议你先玩弄一下代码,理解它,然后你会发现它很容易。 - kapa

    4
    如何按属性获取唯一值
    function groupBy(items,propertyName)
    {
        var result = [];
        $.each(items, function(index, item) {
           if ($.inArray(item[propertyName], result)==-1) {
              result.push(item[propertyName]);
           }
        });
        return result;
    }
    

    使用方法

    var catalog = { products: [
       { category: "Food & Dining"},
       { category: "Techonology"},
       { category: "Retail & Apparel"},
       { category: "Retail & Apparel"}
    ]};
    
    var categoryNames = groupBy(catalog.products, 'category');
    console.log(categoryNames); 
    

    1

    var catalog={
        products : [
            { category: 'fos', name: 'retek' },
            { category: 'fos', name: 'item' },
            { category: 'nyedva', name: 'blabla' },
            { category: 'fos', name: 'gihi' },
        ]
    };
    console.log(_.uniq(_.map(catalog.products, 'category')));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

    使用 _uniq

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接