0

I've got a remote JSON file that contains the list of the last 100 users who logged into a service. This JSON is updated constantly and lists the users from the most recently logged in to the "least recently" logged in.

If the user who appears as number X logs back in, they get removed from their position X and put back at the very top of the JSON at position [0].

I retrieve the JSON every 5 minutes. What I'd like to do is detect the differences between the old object oldUsers and the new newUsers and store them in another object that would only contain the users who are present in newUsers but not in oldUsers. I have no real idea as to how to achieve this.

Here's the JSON structure:

[{
    "id":"foo09",
    "name":"John",
    "age":28
},    {
    "id":"bar171",
    "name":"Bryan",
    "age":36
},
...
]

Is there a rather straightforward way to do it? Thanks!

Stephanie D.
  • 119
  • 1
  • 10
  • 2
    Define *differences*. What output do you expect? – Ionică Bizău Jun 30 '14 at 12:14
  • Straightforward? More than for each element in `newUsers` comparing with each element in `oldUsers` and if not found put in new array? – PeterKA Jun 30 '14 at 12:18
  • Parse both JSON >> Put `id` in array, [Diff two array in jQuery](http://stackoverflow.com/a/10927963/1008278) make sure your newJson array is in 2nd array. This is very Straight forward. :P – VenomVendor Jun 30 '14 at 12:23

1 Answers1

0

You need to write your own diff algorithm. Here is one I whipped up in JSBin:

I will need a utility function to merge two arrays (Underscore would help here).

function mergeArrays(val1, val2) {
  var results = val1.splice(0);
  val2.forEach(function(val) {
    if (val1.indexOf(val) < 0) {
      results.push(val);
    }
  });
  return results;
}

Diff algorithm

function diff(val1, val2) {
  var results  = [];
  var origKeys = Object.keys(val1);
  var newKeys  = Object.keys(val2);

  mergeArrays(origKeys, newKeys)
    .forEach(function(key) {
      if (val1[key] === val2[key]) { return; }
      var result = {
        key:   key,
        orig:  val1[key],
        'new': val2[key]
      };
      if (val1[key] == null) {
         result.type = 'add';
      } else if (val2[key] == null) {
        result.type = 'delete';
      } else {
        result.type = 'change';
      }
      results.push(result);
    });
  return results;
}
Sukima
  • 9,965
  • 3
  • 46
  • 60