[英]Inverse of JavaScript Object.assign
I have a flat JavaScript object called dictionary
that I want to update based on other flat objects.我有一个名为
dictionary
的平面 JavaScript 对象,我想根据其他平面对象更新它。 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.有时我想将对象的每个属性添加到
dictionary
,有时我想删除dictionary
中存在于另一个对象中的每个键。 I'll be using the values of those properties later, but for the sake of managing dictionary
, I only care about their names.稍后我将使用这些属性的值,但为了管理
dictionary
,我只关心它们的名称。
From this question, I know how to merge properties (using, for instance, Object.assign
).从这个问题,我知道如何合并属性(例如,使用
Object.assign
)。 How can I do the inverse of that?我该如何做相反的事情?
Object.unassign
doesn't exist, but is there anything similar? Object.unassign
不存在,但有没有类似的东西?
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) (尽管您可以更改
Object.prototype
并向其添加此unassign
函数,但改变内置对象是非常糟糕的做法 - 最好制作独立函数)
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' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.