Open In App

JavaScript Program to Implement Own Object Assign Method

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s create a custom function called assign that does exactly what Object.assign() does. It will take one or more objects as sources and a target object. Then, it will copy all the properties we can loop over (called enumerable properties) from the source objects to the target object. If a property already exists in the target with the same name, its value will be overwritten.

These are the following methods to Implement Own Object Assign Method:

Using Basic Looping

This method iterates through the source objects using a for loop and uses a conditional statement to determine whether the property is already present in the target object before assigning it.

Example: The keyword is assigned. The assign function is used to merge properties from multiple source objects into a single target object.

JavaScript
function assign(target, ...sources) {
  for (const source of sources) {
    if (source) {
      for (const key in source) {
        if (Object.prototype.hasOwnProperty.
           call(source, key)) {
          target[key] = source[key];
        }
      }
    }
  }
  return target;
}

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, b: 4 };

const merged = assign({}, obj1, obj2);
console.log(merged); 

Output
{ a: 1, b: 4, c: 3 }

Using Object.keys and forEach

This method retrieves all of the keys from the source objects using Object.keys, then loops through them using forEach. After that, bracket notation is used to access dynamic properties during assignment.

Example: JavaScript’s `assign` function merges properties from multiple source objects into a target object, exemplified by the code snippet merging `obj1` and `obj2`.

JavaScript
function assign(target, ...sources) {
  sources.forEach(source => {
    if (source) {
      Object.keys(source).forEach(key => 
        target[key] = source[key]);
    }
  });
  return target;
}

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, b: 4 };

const merged = assign({}, obj1, obj2);
console.log(merged); 

Output
{ a: 1, b: 4, c: 3 }

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads