JavaScript Deep Merge Objects
Last Updated : Mar 11, 2024
IN - JavaScript | Written & Updated By - Anjali
In this article we will show you the solution of JavaScript deep merge objects, in the example below we will use the spread method to deep merge objects in JavaScript.
Using the spread syntax for object merging allows you to construct new objects by mixing properties from existing objects in a succinct and expressive manner.
Spread method: this method is used to merge two objects and return a new object.
the syntax for the spread method is (…).
This method creates a copy of a nested object.
Step By Step Guide On JavaScript Deep Merge Objects :-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript deep merge objects</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css"> <style> body{ background-color: aliceblue; font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; } h1{ color : rgb(95, 194, 95) ; font-size: 25px; font-weight : bolder ; } h3{ color : rgb(95, 194, 95) ; font-size: 20px; } </style> </head> <body> </head> <body> <center> <h1> TALKERSCODE </h1> <h3> JavaScript deep merge objects </h3> </center> <script> const array1 = { name: "peter", age: 20, gender: "male", city: "Newyork", } ; const array2 = { name: "mary", age: 30, gender: "Female", city: "paris", } ; const NewArray = { ...array1, ...array2, } ; console.log(NewArray) ; </script> </body> </html>
- Specifying the HTML version of a file is done by writing <!DOCTYPE html> in the HTML code.
- The <HTML> tag, indicating the root of an HTML document, should be included and closed with the </html> tag at the end.
- Metadata for the HTML file is contained within the <head> tag, which is terminated with the </head> tag.
- The HTML document's title is defined using the <title> tag, followed by the </title> tag.
- Styling for the HTML page will be achieved by utilizing an external CSS file.
- CSS can be added using the <style> tag.
- JavaScript can be written within the <script> tag, and it should be closed with the </script> tag.
- Using const to create one object with some keys such as Name, age, gender and city. Add values to the keys respectively.
- Again use const to create another object with some different keys and values.
- Now create another new array to store the merged array. now using the spread method.
- For displaying the merged object use console.log().
- We can see the merged object in the console terminal of the webpage
Conclusion :-
At last, in conclusion, we can say that with this article’s help, we know deep merge objects using JavaScript.
I hope this article on JavaScript deep merge objects helps you and the steps and method mentioned above are easy to follow and implement.