简体   繁体   English

如何使用Object.assign()函数复制/覆盖对象?

[英]How to copy/overwrite an object using Object.assign() function?

How to fully copy / overwrite an object using Object.assign()? 如何使用Object.assign()完全复制/覆盖对象? If there would be another approach, it would be highly appreciated. 如果有另一种方法,将不胜感激。 :) The purpose is to update the existing object to its new value. :)目的是将现有对象更新为新值。

Below is my code snippet and the expected result should be the same as the value of object2 only. 以下是我的代码段,预期结果应仅与object2的值相同。

Expected result: { a: 8, b: 7 } 预期结果:{a:8,b:7}

 const object1 = { a: 1, b: 2, c: { d: 3 } }; const object2 = { a: 8, b: 7 }; Object.assign(object1, object2); console.log(object1); 

For keeping the same object reference, you could remove all properties in advance and then assign the wanted properties with Object.assign . 为了保持相同的对象引用,您可以预先删除所有属性,然后使用Object.assign分配所需的属性。

 const object1 = { a: 1, b: 2, c: { d: 3 } }; const object2 = { a: 8, b: 7 }; Object.assign( Object.keys(object1).reduce((o, k) => (Reflect.deleteProperty(o, k), o), object1), object2 ); console.log(object1); 

IE IE

 var object1 = { a: 1, b: 2, c: { d: 3 } }, object2 = { a: 8, b: 7 }; Object.keys(object2).reduce( function (object, key) { object[key] = object2[key]; return object; }, Object.keys(object1).reduce(function (object, key) { delete object[key]; return object; }, object1) ); console.log(object1); 

If you want to override the object1 properties with those from object2 , you need to do it like this: 如果你想覆盖object1与那些从性能object2 ,你需要做的是这样的:

object1 = Object.assign({}, object2);

But with this you need to declare object1 with var keyword so you can assign a new value to it. 但是与此相关的是,您需要使用var关键字声明object1 ,以便可以为其分配一个新值。

Demo: 演示:

 var object1 = { a: 1, b: 2, c: { d: 3 } }; const object2 = { a: 8, b: 7 }; object1 = Object.assign({}, object2); console.log(object1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM