- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Union of two objects
We have one object like this −
const obj1 = { name: " ", email: " " };
and another like this −
const obj2 = { name: ['x'], email: ['y']};
We are required to write a JavaScript function that takes in two such objects. and want the output to be the union like this −
const output = { name: {" ", [x]}, email: {" ", [y]} };
Example
The code for this will be −
const obj1 = { name: " ", email: " " }; const obj2 = { name: ['x'], email: ['y']}; const objectUnion = (obj1 = {}, obj2 = {}) => { const obj3 = { name:[], email:[] }; for(let i in obj1) { obj3[i].push(obj1[i]); } for(let i in obj2) { obj3[i].push(obj2[i]); } return obj3; }; console.log(objectUnion(obj1, obj2));
Output
And the output in the console will be −
{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }
Advertisements