How to Copy Object Attributes in JavaScript?

Estimated read time 2 min read

To copy attributes (properties and values) from one object to another in JavaScript, you can use the spread operator (...) or Object.assign().

Here’s an example using the spread operator:

let source = {
  name: "John",
  age: 30,
  city: "New York"
};

let target = {};

target = {
  ...source
};

console.log(target);
// Output: { name: "John", age: 30, city: "New York" }

In this example, we first create an object source with three attributes. Then, we create an empty object target. Finally, we use the spread operator to create a new object that combines the properties of target and source, which results in a shallow copy of the properties and values of source into target.

Here’s an example using Object.assign():

let source = {
  name: "John",
  age: 30,
  city: "New York"
};

let target = {};

target = Object.assign({}, source);

console.log(target);
// Output: { name: "John", age: 30, city: "New York" }

In this example, we use the Object.assign() method to merge the properties of the target object, an empty object literal, and the source object. The first argument to Object.assign() is the target object, and the second argument is the source object, from which the properties will be copied. The method returns the target object after the properties have been merged.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply