How to use Object.keys and forEach In Javascript
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`.
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 }
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