- 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
Filter an object based on an array JavaScript
Let’s say. we have an array and an object like this −
const arr = ['a', 'd', 'f']; const obj = { "a": 5, "b": 8, "c": 4, "d": 1, "e": 9, "f": 2, "g": 7 };
We are required to write a function that takes in the object and the array and filter away all the object properties that are not an element of the array. So, the output should only contain 3 properties, namely: “a”, “d” and “e”.
Let’s write the code for this function −
Example
const arr = ['a', 'd', 'f']; const obj = { "a": 5, "b": 8, "c": 4, "d": 1, "e": 9, "f": 2, "g": 7 }; const filterObject = (obj, arr) => { Object.keys(obj).forEach((key) => { if(!arr.includes(key)){ delete obj[key]; }; }); }; filterObject(obj, arr); console.log(obj);
Output
The output in the console will be −
{ a: 5, d: 1, f: 2 }
Advertisements