kainlite kainlite - 5 months ago 107
Javascript Question

JQuery opposite of extend (reduce objects)

I'm facing the next issue, I can merge/extend objects and works pretty well, but now I need to do the opposite of extending an object, JQuery doc:

var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};

// Merge object2 into object1, recursively
$.extend( true, object1, object2 );

// Result
{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}


Which is cool, and it works great, but how do I get the opposite operation, for example to get an output like this:

{"apple":0,"banana":{"weight":52},"cherry":97}

Answer

There is no such function, but you can write your own:

$.prototype.reduce = function reduce(obj1, obj2) {
  for (var k in obj2) {
    if (obj1.hasOwnProperty(k) && obj2.hasOwnProperty(k)) {
      if (typeof obj1[k] == "object" && typeof obj2[k] == "object") {
         reduce(obj1[k], obj2[k]);
      }
      else delete obj1[k];
    }
  }
}