How to Copy Specific Properties from One Object to Another in JavaScript?

Estimated read time 2 min read

To copy specific properties 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 = {
  ...target,
  name: source.name,
  age: source.age
};

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

In this example, we first create an object source with three properties. Then, we create an empty object target. Next, we use the spread operator to create a new object that combines the properties of target and the properties we want to copy from source, which are name and age in this case.

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

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

let target = {};

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

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

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

Please note that these methods only create a shallow copy of the properties, meaning that if the properties are objects or arrays, only the references to those objects are copied, not the objects themselves. To create a deep copy of the properties, you can use a deep cloning library, such as Lodash’s _.cloneDeep(), or write your own deep cloning function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply