Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Create an object based on 2 others in JavaScript
In JavaScript, you often need to combine properties from multiple objects into a new one. There are several modern approaches to achieve this without modifying the original objects.
Problem Statement
Given two objects with properties and methods, we want to create a third object that contains all properties from both:
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};
// Goal: Create object with properties from both a and b
Using Object Spread Operator (Recommended)
The modern ES6 spread operator provides the cleanest solution:
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};
const combined = { ...a, ...b };
console.log(combined);
combined.af(); // Test method from object a
combined.bf(); // Test method from object b
{ a: 1, af: [Function: af], b: 2, bf: [Function: bf] }
1
2
Using Object.assign()
Another modern approach using the built-in Object.assign() method:
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};
const combined = Object.assign({}, a, b);
console.log(combined);
{ a: 1, af: [Function: af], b: 2, bf: [Function: bf] }
Custom Extension Function
For more control or compatibility with older JavaScript versions:
const extend = function() {
let i, j, res = (arguments[0] || {});
for (i = 1; i < arguments.length; i++) {
const x = arguments[i];
for (j in x) {
if (x.hasOwnProperty(j)) {
res[j] = x[j];
}
}
}
return res;
};
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};
const combined = extend({}, a, b);
console.log(combined);
{ a: 1, af: [Function: af], b: 2, bf: [Function: bf] }
Comparison
| Method | Browser Support | Readability | Performance |
|---|---|---|---|
| Spread Operator | ES6+ | Excellent | Fast |
| Object.assign() | ES6+ | Good | Fast |
| Custom Function | All versions | Fair | Slower |
Key Points
- All methods create shallow copies of the original objects
- Original objects remain unchanged
- If properties have the same name, later objects override earlier ones
- Methods are copied by reference, maintaining their functionality
Conclusion
Use the spread operator { ...a, ...b } for modern JavaScript projects. It's the most readable and performant approach for combining object properties while preserving the original objects.
Advertisements
