0

So, let's say i have object A and object B. Object A has a number of children where object B has a number of children that are the same. How do I find out what are the differences the ones missing in object B and the ones added in object A and then put them into their own object or two-dimensional array.

For example, the first array being those that are added to second, being subracted:

var changes = [["google.com", "yahoo.com"],["facebook.com", "bing.com"]]

I am trying compare a snapshot of stored bookmarks and the current bookmarks list using crossrider.

user2491588
  • 17
  • 1
  • 4
  • 1
    You have to iterate and compare the string values (or whatever) of each key/value pair etc. To get some help with this you will have to post the objects that are supposed to be compared against each other, and not just the array you'd like to end up with. – adeneo Jul 02 '13 at 22:31

2 Answers2

1

I believe this is a follow on from the following questions, and so I will combine them all into a single code example that runs in the background scope (background.js): realtime with non-event programming, crossrider: store snapshot of bookmarks in local database and compare to current bookmarks list

So for the getChanges function, I prefer to convert the bookmark trees into hash lists and then compare the lists for changes. In the following example, I use createHash to create the hash lists using cloneNode to create a shallow clone of the node objects, and then in getChanges I compare the hash lists for additions, modifications, and deletions:

appAPI.ready(function() {
  // Poll every 30 seconds
  setInterval(function() {
    appAPI.db.async.get('prevBookmarks', function(value) {
      // Load or initialize the previous bookmarks list
      var prevBookmarks = (value) ? value : {};

      // Get current bookmarks
      appAPI.bookmarks.getTree(function(nodes) {
        // Save bookmark hash for comparison in next interval
        appAPI.db.async.set('prevBookmarks', createHash(nodes[0]));

        // Get hash list of curent bookmarks
        var currBookmarks = createHash(nodes[0]);

        // Get changes between the lists
        var changes = getChanges(prevBookmarks, currBookmarks);

        // Post changes to your API server
        appAPI.request.post({
          url: http://yourAPIserver.com,
          postData: changes,
          contentType: 'application/json'
        });
      });
    });
  }, 30 * 1000);

  // Function to create a hash list from a bookmark tree
  function createHash(node) {
    var hash = {};
    if (typeof node === 'object') hash[node._id] = cloneNode(node);

    if (node.isFolder && typeof node.children !== 'undefined' && node.children.length > 0)  {
      node.children.forEach(function(child) {
        var childHash = createHash(child);
        for (var key in childHash) {
          if (!hash[key]) hash[key] = cloneNode(childHash[key]);
        }
      });
    }
    return hash;
  }

  // Function to create shallow clones of bookmark nodes
  function cloneNode(node) {
    var clone = appAPI.JSON.parse(appAPI.JSON.stringify(node));
    delete clone.children;
    delete clone.dateAdded;
    return clone;
  }

  // Get changes between current and previous bookmark hash lists
  function getChanges(prev, curr) {
      // Initialize return object
      var changes = {added:{}, modified:{}, removed:{}};

      // Search for added or modified nodes
      for (var key in curr) {
          if (!prev[key])
            changes.added[key] = curr[key];
          else if (appAPI.JSON.stringify(prev[key]) !== appAPI.JSON.stringify(curr[key]))
            changes.modified[key] = curr[key];
      }

      // Search for removed nodes
      for (var key in prev) {
          if (!curr[key])
            changes.removed[key] = prev[key];
      }
      return changes;
  }
});

Disclaimer: I am a Crossrider employee

Community
  • 1
  • 1
Shlomo
  • 3,763
  • 11
  • 16
0

If the two objects to be compared are both one-dimensional arrays, then simply use the set arithmetic functions in Underscore.js, such as _.difference and _.intersection.

Or, use the same logic, which for intersect (unoptimized) is as simple as:

array1.filter(function(v){return array2.indexOf(v)!==-1);});

If you're looking for a generalized way to find the diff between two arbitrary objects of any depth and complexity, this is not a well-defined problem.