Himanshu Yadav
Himanshu Yadav

Reputation: 13585

JSON data parsing, sorting and merge with jquery

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?

Upvotes: 1

Views: 259

Answers (2)

jcolebrand
jcolebrand

Reputation: 16035

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

Then sort the second object by the count property

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707976

It's not clear to me exactly what you're asking because the data you present is not shown in actual javascript syntax. But, to iterate through all the properties of an object, you would do this:

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

Note: the properties of an object have no defined order.

Upvotes: 1

Related Questions