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
How to add properties from one object into another without overwriting in JavaScript?
When merging objects in JavaScript, you often want to add properties from one object to another without overwriting existing values. This preserves the original object's data while incorporating new properties.
The Problem
Consider these two objects where some properties overlap:
var first = {key1: 100, key2: 40, key3: 70};
var second = {key2: 80, key3: 70, key4: 1000};
console.log("First object:", first);
console.log("Second object:", second);
First object: { key1: 100, key2: 40, key3: 70 }
Second object: { key2: 80, key3: 70, key4: 1000 }
We want to add key4 from the second object to the first, but keep the original values for key2 and key3.
Using hasOwnProperty() Method
The hasOwnProperty() method checks if a property exists directly on an object, allowing us to avoid overwriting existing properties:
var first = {key1: 100, key2: 40, key3: 70};
var second = {key2: 80, key3: 70, key4: 1000};
function addPropertiesWithoutOverwriting(first, second) {
for (var key in second) {
if (second.hasOwnProperty(key) && !first.hasOwnProperty(key)) {
first[key] = second[key];
}
}
return first;
}
console.log(addPropertiesWithoutOverwriting(first, second));
{ key1: 100, key2: 40, key3: 70, key4: 1000 }
Using Object.assign() with Reversed Parameters
A more concise approach uses Object.assign() by reversing the parameter order:
var first = {key1: 100, key2: 40, key3: 70};
var second = {key2: 80, key3: 70, key4: 1000};
// Merge without overwriting first object's properties
var result = Object.assign({}, second, first);
console.log("Original first:", {key1: 100, key2: 40, key3: 70});
console.log("Merged result:", result);
Original first: { key1: 100, key2: 40, key3: 70 }
Merged result: { key2: 40, key3: 70, key4: 1000, key1: 100 }
Using Spread Operator (ES6)
The spread operator provides the cleanest syntax for modern JavaScript:
const first = {key1: 100, key2: 40, key3: 70};
const second = {key2: 80, key3: 70, key4: 1000};
// Spread second first, then first to avoid overwriting
const merged = {...second, ...first};
console.log("Merged with spread:", merged);
Merged with spread: { key2: 40, key3: 70, key4: 1000, key1: 100 }
Comparison
| Method | Modifies Original? | Browser Support | Readability |
|---|---|---|---|
hasOwnProperty() |
Yes | All browsers | Verbose |
Object.assign() |
No (with empty object) | ES6+ | Good |
| Spread operator | No | ES6+ | Excellent |
Conclusion
Use the spread operator for modern JavaScript applications, or hasOwnProperty() for older environments. Both methods effectively preserve existing properties while adding new ones.
