【问题标题】:Get unique results from JSON array using jQuery使用 jQuery 从 JSON 数组中获取唯一结果
【发布时间】:2011-10-04 13:23:21
【问题描述】:

我有这段代码可以将我的数组中的“类别”显示到一个 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"},

【问题讨论】:

    标签: javascript jquery arrays json


    【解决方案1】:

    我不知道您的 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 不能重复,您可以给它们一个小前缀)。

    【讨论】:

    • 似乎不起作用.. 我会及时通知您。如果您有时间查看,我会使用数组中的代码编辑我的问题。再次感谢。
    • @JFFF 我将您的示例对象加载到我的代码中:jsFiddle Demo #2。似乎对我有用。随意调整我的小提琴以获得您期望的结果(也许您想将其他值添加到 categories 数组中)。
    • 你好,有没有办法让它对任何其他字段都是唯一的,所以让我们说(使用类别 json)你想要所有颜色没有任何重复。
    • @Djeroen 是的,您只需稍微更改代码即可。我建议你玩代码,理解它,然后你会发现它很容易。
    【解决方案2】:

    如何通过属性获取唯一值

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

    【讨论】:

      【解决方案3】:

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

      使用_uniq

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 2013-07-09
        • 2018-09-13
        相关资源
        最近更新 更多