7

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' }
crass_sandwich
  • 176
  • 3
  • 9

2 Answers2

8

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)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Another beautiful way I found is via object destructuring…

const dictionary = { foo: 'bar', baz: 'qux', spam: 'spam' };
const {foo, baz, ...newDictionary} = dictionary;
console.log(newDictionary) // { spam: 'spam' }
bigOmega ツ
  • 371
  • 3
  • 13