使用jQuery从JSON数组中获取独特的结果

JFF*_*FFF 12 javascript arrays jquery json

我有这个代码块,将我的数组中的"类别"显示为一个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');
}
Run Code Online (Sandbox Code Playgroud)

这是我的数组的代码:

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"},
Run Code Online (Sandbox Code Playgroud)

kap*_*apa 22

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

var categories = [];

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

jsFiddle演示

categories将保留您需要的唯一类别,您可以使用它来构建您的HTML(但要注意这些li元素的ID ,请记住ID不能重复,您可能会给它们一个小前缀).