[英]How i can assign values to the properties of one object to another?
I have two objects like: 我有两个对象,例如:
var a = { a1: 'a1', a2: 'a2', a3: {}}
var b = { a1: 'b1', a2: 'b2', a3: {}}
How i can assign values to the properties of one object to another? 我如何将一个对象的属性值分配给另一个对象?
If i try use a=b
As I get an object a link to b. 如果我尝试使用
a=b
当我得到一个对象时,指向b的链接。 I just want to equate the value of the properties. 我只想等同于属性的值。
Use Object.assign()
. 使用
Object.assign()
。
Object.assign(b, a); // Assign all properties of a to b. Changing b in the process.
Be advised: Object.assign()
it relatively new, and is not supported in Internet Explorer as of yet. 建议:
Object.assign()
相对较新,并且Internet Explorer Object.assign()
尚不支持。
There are lot's of way to clone an object. 克隆对象有很多方法。
The two elegant (may not be the most efficient) ways are: 两种优雅的(可能不是最有效的)方式是:
Without JQUERY - Using the serialize\\deserialize way 不使用JQUERY-使用序列化\\反序列化方式
var obj = { a1: 'a1', a2: 'a2', a3: {}}
var cloned = JSON.parse(JSON.stringify(obj));
With JQUERY - Using $.extend : 使用 jQuery -使用$ .extend :
var obj = { a1: 'a1', a2: 'a2', a3: {}}
var cloned = $.extend({}, obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.