
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 }
- Related Questions & Answers
- Filter the properties of an object based on an array and get the filtered object JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- Filter array based on another array in JavaScript
- How to filter documents based on an array in MongoDB?
- Modify an array based on another array JavaScript
- Create an object based on 2 others in JavaScript
- How to filter object array based on attributes in jQuery?
- Shuffling string based on an array in JavaScript
- Splitting an array based on its first value - JavaScript
- Shifting string letters based on an array in JavaScript
- JavaScript example to filter an array depending on multiple checkbox conditions.
- Filter null from an array in JavaScript?
- Sort object array based on another array of keys - JavaScript
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript
Advertisements