1

I have a long array of pks. Which has been converted into a json object pk:count This how I created it

var count = {};
topPKs=[];
topPKs.push(pk1);
topPKs.push(pk2);
topPKs.push(pk3);
topPKs.push(pk1);
topPKs.push(pk1);
$.each(topPKs, function(key, value) {
                    if(!count[value])
                        count[value] = 1;
                    else
                        count[value]++;
                });

This is how it looks in console:

Object
511909695: 3
523212317: 2
530009912: 3
532408581: 2
533498979: 1
555813096: 1
574723371: 1
574938523: 1
580120684: 6
584152864: 2

There is an object array with pk and name. So when I say Object.pk, it returns pk value.
Not all pks in the second object array present in the first object with pk:count.

0: Object
    pk: "609819451"
    name: "Some Name"
1: Object
2: Object

Now I want to sort second object array based on the pk count present in the first object. I am not sure how would traverse through all the pks in the first object. Because it is not an array. Should I create it a different way?

  1. How would I traverse the first object with jquery?
  2. How would I sort the second object array based on the count of pk in first PK?
4

2 回答 2

1
for(var k1 in obj1){ var record = obj1[k1];
  for(var k2 in obj2){ 
    if (obj2[k2].pk == record)
       obj2[k2].count = record.count;
  }
}

然后按 count 属性对第二个对象进行排序

obj2.sort(function _internalSort(l,r){var x = l.count || 0, y = r.count || 0;return y - x; })
//this handles the case where a value appears in the second list but not the first
//by forcing all values to have a count for the sorting method
于 2013-01-10T22:42:28.513 回答
1

我不清楚你到底在问什么,因为你提供的数据没有以实际的 javascript 语法显示。但是,要遍历对象的所有属性,您可以这样做:

for (var prop in obj) {
    var item = obj[prop];
    // prop is the property name
    // item is the value of the property
}

注意:对象的属性没有定义的顺序。

于 2013-01-10T22:43:13.023 回答