- Trending Categories
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
How to concatenate two JavaScript objects with plain JavaScript ?
Suppose we have two objects defined like this −
const obj1 = { id1: 21, name1: "Kailash" }; const obj2 = { id2: 20, name2: "Shankar" };
We are required to write a JavaScript function that takes in two such objects and merges into a single object.
In other words, we are required to more or less implement the functionality of Object.assign() function.
Example
The code for this will be −
const obj1 = { id1: 21, name1: "Kailash" }; const obj2 = { id2: 20, name2: "Shankar" }; const concatObjects = (...sources) => { const target = {}; sources.forEach(el => { Object.keys(el).forEach(key => { target[key] = el[key]; }); }); return target; } console.log(concatObjects(obj1, obj2));
Output
And the output in the console will be −
{ id1: 21, name1: 'Kailash', id2: 20, name2: 'Shankar' }
Advertisements