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

时间:2011-07-13 14:21:58

标签: javascript jquery arrays 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');
}

这是我的数组的代码:

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 个答案:

答案 0 :(得分:22)

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

var categories = [];

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

jsFiddle Demo

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

答案 1 :(得分:3)

如何按属性获取唯一值

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); 

答案 2 :(得分:0)

&#13;
&#13;
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')));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
&#13;
&#13;
&#13;

使用_uniq