Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of JavaScript Object.assign

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' }
like image 690
crass_sandwich Avatar asked Jan 27 '23 20:01

crass_sandwich


1 Answers

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)

like image 70
CertainPerformance Avatar answered Jan 30 '23 10:01

CertainPerformance