This tutorial aims to teach you how to use the $.extend()
method in jQuery to merge and extend JavaScript objects.
By the end of this tutorial, you will be able to:
$.extend()
method effectively to combine and extend objectsBasic knowledge of JavaScript and jQuery is required. You also need to have jQuery library installed or a CDN link to jQuery in your HTML file.
The $.extend()
function in jQuery is used to merge the contents of two or more objects into the first object. The function's syntax is as follows:
$.extend(target, object1, object2, ..., objectN)
target
is the object that will receive the new properties.object1
, object2
, ..., objectN
are the objects containing properties to be merged into the target object.If the first argument passed to $.extend()
is true
, a deep copy is performed. This means that properties in the source objects are recursively copied into the target object.
$.extend(true, target, object1, object2, ..., objectN);
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend(object1, object2);
console.log(object1);
The output will be:
{
apple: 0,
banana: { price: 200 },
cherry: 97,
durian: 100
}
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Perform a deep merge
$.extend(true, object1, object2);
console.log(object1);
The output will be:
{
apple: 0,
banana: { weight: 52, price: 200 },
cherry: 97,
durian: 100
}
In a deep merge, the properties of banana
in object1
and object2
are merged together.
In this tutorial, we've learned how to:
$.extend()
method.$.extend()
.For further learning, you can explore other jQuery methods for manipulating objects and arrays.
Write code to merge the following objects into one:
var object1 = {
cat: 10,
dog: 20
};
var object2 = {
bird: 30,
fish: 40
};
$.extend(object1, object2);
console.log(object1);
Perform a deep merge on the following objects:
var object1 = {
cat: 10,
dog: { weight: 20, price: 100 }
};
var object2 = {
dog: { price: 200 },
bird: 30
};
$.extend(true, object1, object2);
console.log(object1);
Try to create more complex objects and practice merging them. Play around with deep and simple merges to fully understand their differences.