2

重複の可能性:
JavaScriptオブジェクトをプロパティ値で並べ替える

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に挿入できるようにすることです。

  • ライセンス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 );
}();

これは私が欲しいもののほとんどを私に与えます、キーを持つオブジェクト:値

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

しかし、私はそれをどうやって使うのか分かりません。右の数字の列を並べ替えて、関連するキーをそのままにしておく必要があります。考え?ありがとうございました!

4

1 に答える 1

6

オブジェクトをその値で並べ替えることはできません。あなたができることは、それをオブジェクトの配列に変換し、代わりにそれをソートすることです。何かのようなもの:

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;

/codeはテストされていません

于 2013-01-13T01:53:50.077 に答える