简体   繁体   English

我如何将一个对象的属性值分配给另一个对象?

[英]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()尚不支持。

A polyfill for it is available here . 在此处使用它的polyfill。

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.

相关问题 如何将状态值分配给另一个对象? - How can I assign the values of state to another object? 如何从一堆计算值中一个接一个地分配Vue对象的属性? - How do I assign a Vue object's properties, one by one, from a bunch of computed values? 如何将特定属性从一个 object 分配给另一个 - How to assign specific properties from one object to another 如何使用记录集将一个对象值分配给另一个.object - How to assign one object values to another .object using recordset 无法使用“ for…in”循环为对象的属性分配值 - Can't assign values to properties of object with a “for…in” loop 如何将 object 中的属性分配给 HTML 元素 - How can I assign properties from an object to a HTML element 如何将属性和值动态分配给 Javascript 中的 object - How to dynamically assign properties and values to an object in Javascript 如何将数组值分配给其他对象的对象键? - How can I assign array values into object keys for other object? TypeScript - 将一个对象的所有属性分配给另一个对象的速记方式 - TypeScript - Shorthand way to assign all properties of one object to another 尝试将属性从一个 object 分配给另一个时出现 TypeScript 错误 - TypeScript errors while trying to assign properties from one object to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM