How to Copy Fields from One JavaScript Object to Another?

Estimated read time 1 min read

You can copy fields from one JavaScript object to another using the following code:

let source = {
  field1: 'value1',
  field2: 'value2',
  field3: 'value3'
};

let destination = {};

for (let key in source) {
  destination[key] = source[key];
}

console.log(destination);

In this example, we first define a source object with three fields. Then, we create an empty destination object.

We use a for...in loop to iterate over all the enumerable properties of the source object. For each property, we add a property with the same name to the destination object and set its value to the value of the corresponding property in the source object.

After the loop, the destination object will contain all the properties of the source object.

You can use this pattern to copy the fields from one object to another, or to create a shallow copy of an object. Keep in mind that this is a shallow copy, so if the properties of the source object are references to objects, then the corresponding properties in the destination object will also be references to the same objects.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply