Algorithm
-
Define a Function:
- Create a function, let's call it
mergeObjects
, that takes two objects as parameters.
- Create a function, let's call it
-
Initialize a Result Object:
- Inside the function, create a new object to store the merged properties. Let's call it
mergedObject
.
- Inside the function, create a new object to store the merged properties. Let's call it
-
Iterate Over the First Object:
- Use a
for...in
loop to iterate over the properties of the first object. - For each property, add it to the
mergedObject
.
- Use a
-
Iterate Over the Second Object:
- Repeat the same process for the second object.
- Check if the property already exists in the
mergedObject
. If it does, you may choose to handle this situation based on your requirements (e.g., overwrite, skip, merge values, etc.).
-
Return Merged Object:
- Once both objects have been iterated and their properties added to the
mergedObject
, return the result.
- Once both objects have been iterated and their properties added to the
Code Examples
#1 Code Example- Merge Property of Two Objects Using Object.assign()
Code -
Javascript Programming
// program to merge property of two objects
// object 1
const person = {
name: 'Jack',
age:26
}
// object 2
const student = {
gender: 'male'
}
// merge two objects
const newObj = Object.assign(person, student);
console.log(newObj);
Copy The Code &
Try With Live Editor
Output
{
name: "Jack",
age: 26,
gender: "male"
}
name: "Jack",
age: 26,
gender: "male"
}
#2 Code Example- Merge Property of Two Objects Using Spread Operator
Code -
Javascript Programming
// program to merge property of two objects
// object 1
const person = {
name: 'Jack',
age:26
}
// object 2
const student = {
gender: 'male'
}
// merge two objects
const newObj = {...person, ...student};
console.log(newObj);
Copy The Code &
Try With Live Editor
Output
{
name: "Jack",
age: 26,
gender: "male"
}
name: "Jack",
age: 26,
gender: "male"
}
Demonstration
JavaScript Programing Example to Merge Property of Two Objects-DevsEnv