Algorithm


  1. Define a Function:

    • Create a function, let's call it mergeObjects, that takes two objects as parameters.
  2. Initialize a Result Object:

    • Inside the function, create a new object to store the merged properties. Let's call it mergedObject.
  3. 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.
  4. 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.).
  5. Return Merged Object:

    • Once both objects have been iterated and their properties added to the mergedObject, return the result.

 

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

x
+
cmd
{
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

x
+
cmd
{
name: "Jack",
age: 26,
gender: "male"
}
Advertisements

Demonstration


JavaScript Programing Example to Merge Property of Two Objects-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way