- 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
Object difference in JavaScript
We are required to write a JavaScript function that takes in two objects (possibly nested) and returns a new object with key value pair for the keys that were present in the first object but not in the second
Let's write the code for this function −
Example
const obj1 = { "firstName": "Raghav", "lastName": "Raj", "age": 43, "address": "G-12 Kalkaji", "email": "raghavraj1299@yahoo.com", "salary": 90000 }; const obj2 = { "lastName": "Raj", "address": "G-12 Kalkaji", "email": "raghavraj1299@yahoo.com", "salary": 90000 }; const objectDifference = (first, second) => { return Object.keys(first).reduce((acc, val) => { if(!second.hasOwnProperty(val)){ acc[val] = first[val]; }; return acc; }, {}); }; console.log(objectDifference(obj1, obj2));
Output
The output in the console will be −
{ firstName: 'Raghav', age: 43 }
Advertisements
To Continue Learning Please Login
Login with Google