Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 258
kainlite Avatar asked Dec 25 '22 01:12

kainlite


2 Answers

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];
    }
  }
}
like image 95
Liglo App Avatar answered Jan 02 '23 21:01

Liglo App


In JavaScript, you can remove a property from an object entirely by using the delete operator:

var foo = {
  bar: "This is bar"
};
snippet.log(foo.bar);                   // "This is bar"
snippet.log(foo.hasOwnProperty('bar')); // true
delete foo.bar;
snippet.log(foo.hasOwnProperty('bar')); // false
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

So to modify your object, just delete the properties you don't want.


Side note: 99.99% of the time it doesn't matter, but note that deleting properties from objects makes some JavaScript engines fall back on unoptimized "map" versions of objects instead of optimized ones, which means accessing the remaining properties on the object is much slower. Again, it's unusual that it matters, but useful to know for those very rare times when it does.

like image 26
T.J. Crowder Avatar answered Jan 02 '23 22:01

T.J. Crowder