Merge two or more objects together. A vanilla JavaScript equivalent of jQuery's .extend()
function.
Want to learn vanilla JavaScript? Check out "The Vanilla JS Guidebook" and level-up as a web developer. 🚀
Include the code in your script, or load it as an external file.
var extend = function () {
...
};
Pass in two or more objects to extend. For a deep or recursive merge, set the first argument to true
.
// Example objects
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
var object3 = {
apple: 'yum',
pie: 3.214,
applePie: true
};
// Create a new object by combining two or more objects
var newObjectShallow = extend( object1, object2, object3 );
var newObjectDeep = extend( true, object1, object2, object3 );
extend works in all modern browsers, and IE 6 and above.
Please review the contributing guidelines.
The code is available under the MIT License.