
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' ] ] }
- Related Articles
- Python Pandas - Form the Union of two Index objects
- Finding union of two sets in JavaScript
- Python Pandas - Form the Union of two Index objects with different datatypes
- Python Pandas - Form the Union of two Index objects but do not sort the result
- Union of two HashSet in C#
- JavaScript Sum of two objects with same properties
- How to merge two JavaScript objects?
- How to merge properties of two JavaScript Objects dynamically?
- Sort Array of objects by two properties in JavaScript
- How to concatenate two JavaScript objects with plain JavaScript ?
- How to compare two JavaScript Date Objects?
- How to compare two objects in JavaScript?
- Construct objects from joining two strings JavaScript
- Join two objects by key in JavaScript
- Get the union of two sets in Java

Advertisements