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}
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];
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With