How to Merge Two Objects Using jQuery $.extend()
This article provides a practical guide on merging JavaScript objects
using jQuery’s built-in $.extend() method. You will learn
the basic syntax for combining multiple objects, how to handle
conflicting properties, how to avoid mutating the original source
objects, and how to execute deep recursive merges for nested data
structures.
Basic Syntax
The $.extend() utility method merges the contents of two
or more objects into a target object.
$.extend([deep], target, object1, [objectN])deep(optional): A boolean. If set totrue, the merge becomes recursive (deep copy).target: The object that receives the new properties.object1toobjectN: The source objects containing the properties you want to merge.
Shallow Merging Two Objects
By default, $.extend() performs a shallow merge.
Properties from the source objects are copied directly into the target
object.
var object1 = {
name: "John",
role: "Developer"
};
var object2 = {
role: "Senior Developer",
city: "New York"
};
// Merge object2 into object1
$.extend(object1, object2);
console.log(object1);
// Output: { name: "John", role: "Senior Developer", city: "New York" }Avoiding Mutation of the Original Object
In the example above, object1 was modified directly. To
merge two objects into a completely new object without altering the
originals, pass an empty object literal {} as the
target:
var object1 = { a: 1, b: 2 };
var object2 = { b: 3, c: 4 };
var mergedObject = $.extend({}, object1, object2);
console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
console.log(object1); // Output: { a: 1, b: 2 } (Unchanged)If a property name exists in both objects, the property from the latter object overwrites the property in the former.
Deep Merging Nested Objects
A standard shallow merge replaces nested objects entirely if keys
conflict. To recursively combine nested structures instead of
overwriting them, pass true as the first argument.
Shallow Merge Conflict
(Without true):
var defaults = {
settings: {
theme: "light",
notifications: true
}
};
var userPreferences = {
settings: {
theme: "dark"
}
};
var result = $.extend({}, defaults, userPreferences);
console.log(result.settings);
// Output: { theme: "dark" }
// Notice that 'notifications: true' was completely overwritten and lost.Deep Merge Solution (With
true):
var defaults = {
settings: {
theme: "light",
notifications: true
}
};
var userPreferences = {
settings: {
theme: "dark"
}
};
var result = $.extend(true, {}, defaults, userPreferences);
console.log(result.settings);
// Output: { theme: "dark", notifications: true }
// Both nested properties are preserved.