How to use Basic Looping In Javascript
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.
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 }
JavaScript Program to Implement Own Object Assign Method
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:
Table of Content
- Using Basic Looping
- Using Object.keys and forEach
Contact Us