【问题标题】:Javascript - Count duplicate JSON values and sort Count along with associative key? [duplicate]Javascript - 计算重复的 JSON 值并将计数与关联键一起排序? [复制]
【发布时间】:2012-12-27 07:28:21
【问题描述】:

可能重复:
Sorting JavaScript Object by property value

我想在我的 JSON 中获得一些价值的最佳结果。用这个例子更容易解释:

var jsonData = {
  bom: [
        {
            "Component":"Some Thing",
            "Version":"Version ABC",
            "License":"License ABC",
        },
        {
            "Component":"Another Thing",
            "Version":"Version XYZ",
            "License":"License ABC",
        }, 
        etc ....
       ]
}

所以我的目标是确定“许可证 ABC”或其他许可证有 X 次出现,然后我希望能够对这些 key:val 对进行排序以插入到 DOM 中,因为“最流行的 X 许可证是:

  • 许可证 ABC - 100
  • 许可证 XYZ - 70
  • 许可证 123 - 25

现在我有这个:

var countResults = function() {
    var fileLicenses = [];

    for ( var i = 0, arrLen = jsonData.files.length; i < arrLen; ++i ) {
        fileLicenses.push(jsonData.files[i]["License"]);
    }

    keyCount = {};
    for(i = 0; i < fileLicenses.length; ++i) {
        if(!keyCount[fileLicenses[i]]) {
            keyCount[fileLicenses[i]] = 0;
        }

        ++keyCount[fileLicenses[i]];
    }

    console.log( keyCount );
}();

这是我最想要的,一个带有 key : values

的对象
{
    thisKey : 78,
    thatKey :125,
    another key : 200,
    another key : 272,
    another key : 45,
    etc ...
}

但我不知道该怎么做。我只需要对右列的数字进行排序,并让相关的键随行。想法?谢谢!

【问题讨论】:

    标签: javascript json object loops associative-array


    【解决方案1】:

    您不能按对象的值对对象进行排序。您可以做的是将其转换为对象数组并对其进行排序。比如:

    var rank = function(items, prop) {
    
      //declare a key->count table
      var results = {}
    
      //loop through all the items we were given to rank
      for(var i=0;len=items.length;i<len;i++) {
    
        //get the requested property value (example: License)
        var value = items[i][prop];
    
        //increment counter for this value (starting at 1)
        var count = (results[value] || 0) + 1;
        results[value] = count;
      }
    
      var ranked = []
    
      //loop through all the keys in the results object
      for(var key in results) {
    
        //here we check that the results object *actually* has
        //the key. because of prototypal inheritance in javascript there's
        //a chance that someone has modified the Object class prototype
        //with some extra properties. We don't want to include them in the
        //ranking, so we check the object has it's *own* property.
        if(results.hasOwnProperty(key)) {
    
          //add an object that looks like {value:"License ABC", count: 2} 
          //to the output array
          ranked.push({value:key, count:results[key]}); 
        }
      }
    
      //sort by count descending
      return ranked.sort(function(a, b) { return b.count - a.count; });
    }
    

    用法:

    var sorted = rank(jsonData.bom, "License");
    var first = sorted[0].value;
    

    /代码未测试

    【讨论】:

    • 感谢 fencliff!插上电源,效果很好。仍然需要一些时间来理解逻辑,但这正是我所需要的。谢谢!
    • @Matt 我在代码中添加了一些 cmets 来解释逻辑。如果解决方案有效,请不要忘记将答案标记为已接受!
    • 哇。非常感谢 cmets Fencliff。该解决方案从一开始就很好用,但是了解您正在插入的内容总是更好!这有帮助。再次感谢!
    • @Matt,不客气。除非我理解它,否则我不会使用我在互联网上找到的任何代码:)
    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多