JQuery opposite extension (reduce objects)

I ran into the following problem: I can combine / expand objects and work very well, but now I need to do the reverse side of the object extension, 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 this output:

{"apple":0,"banana":{"weight":52},"cherry":97}
+4
source share
3 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];
    }
  }
}
+8
source

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

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.imtqy.com/simple-snippets-console/snippet.js"></script>
Run code

So, to change your object, just delete the properties you don't need.


: 99,99% , , , JavaScript "" , . , , , , .

+1

I also encountered such a problem. I had to implement a recursive reduction operation:

$.reduce({a: 1, b: 2}, {b: 12, e: 13}) => {a: 1, b: 12}

This is how i did it

$.reduce = function reduce(templateObj, toReduce, modifyCopy, doNotAppend) {
    if (!toReduce) {
        return toReduce;
    }
    if (!templateObj) {
        return toReduce;
    }
    // not changing the src toReduce
    var toModify = modifyCopy
        ? $.extend(true, {}, toReduce)
        : toReduce;

    // will append missing properties from templateObj 
    var merged = doNotAppend
        ? toModify
        : $.extend(true, {}, templateObj, toModify);
    // go through all the properties in toReduce or (templateObj + toReduce)
    $.each(merged, function (propName, value) {
        if (!(propName in templateObj)) {
            delete toModify[propName];
            return;
        }
        if (!(propName in toModify)) {
            toModify[propName] = templateObj[propName];
            return;
        }
        if (typeof templateObj[propName] == "object" && typeof toModify[propName] == "object") {
            toModify[propName] = $.reduce(templateObj[propName], toModify[propName]);
        }
    });
    return toModify;
}
+1
source

All Articles