I have a flat JavaScript object called dictionary
that I want to update based on other flat objects. Sometimes I want to add every property of an object to dictionary
and sometimes I want to delete every key in dictionary
that exists in another object. I'll be using the values of those properties later, but for the sake of managing dictionary
, I only care about their names.
From this question, I know how to merge properties (using, for instance, Object.assign
). How can I do the inverse of that? Object.unassign
doesn't exist, but is there anything similar?
For example:
dictionary = { foo: 'bar', baz: 'qux' };
object1 = { spam: 'spam' };
Object.assign(dictionary, object1); // dictionary now has properties: foo, baz, spam
object2 = { foo: 'spam', baz: 'qux' };
Object.unassign(dictionary, object2); // dictionary is now only { spam: 'spam' }
There's no such built-in function, but it would be quite trivial to write your own that accomplishes something like that:
const dictionary = { foo: 'bar', baz: 'qux' };
const object1 = { spam: 'spam' };
const object2 = { foo: 'spam', baz: 'qux' };
Object.assign(dictionary, object1);
const unassign = (target, source) => {
Object.keys(source).forEach(key => {
delete target[key];
});
};
unassign(dictionary, object2);
console.log(dictionary);
(Although you could change Object.prototype
and add this unassign
function to it, mutating the built-in objects is very bad practice - better to make a standalone function)
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