
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge Object Properties Through Unique Field and Print Data in JavaScript
Let’s say we have a students object containing two properties names and marks. The names is an array of object with each object having two properties name and roll, similarly marks is an array of object with each object having properties mark and roll. Our task is to combine the marks and names properties according to the appropriate roll property of each object.
The students object is given here −
const students = { marks: [{ roll: 123, mark: 89 }, { roll: 143, mark: 69 }, { roll: 126, mark: 91 }, { roll: 112, mark: 80 }], names: [{ name: 'Aashish', roll: 126 }, { name: 'Sourav', roll: 112 }, { name: 'Vineet', roll: 143 }, { name: 'Kartik', roll: 123 }] }
Let’s define a function combineProperties that takes in the students object and combines the properties in place i.e., without using any extra space −
const combineProperties = (students) => { const { marks, names } = students; marks.forEach(marksObj => { const { roll } = marksObj; marksObj.name = names.find(namesObj => namesObj.roll ===roll).name; }) delete students['names']; }; combineProperties(students); console.log(students);
The time complexity of this code is O(mn) where m and n are the respective sizes of arrays names and marks and the space complexity of this O(1). However, a new property is being created for each element of marks array.
Here’s the complete code −
Example
const students = { marks: [{ roll: 123, mark: 89 }, { roll: 143, mark: 69 }, { roll: 126, mark: 91 }, { roll: 112, mark: 80 }], names: [{ name: 'Aashish', roll: 126 }, { name: 'Sourav', roll: 112 }, { name: 'Vineet', roll: 143 }, { name: 'Kartik', roll: 123 }] } const combineProperties = (students) => { const { marks, names } = students; marks.forEach(marksObj => { const { roll } = marksObj; marksObj.name = names.find(namesObj => namesObj.roll ===roll).name; }) delete students['names']; }; combineProperties(students); console.log(students);
Output
The console output will be −
{ marks: [ { roll: 123, mark: 89, name: 'Kartik' },{ roll: 143, mark: 69, name: 'Vineet' }, { roll: 126, mark: 91, name: 'Aashish' },{ roll: 112, mark: 80, name: 'Sourav' } ] }