- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the properties of an object based on an array and get the filtered object JavaScript
We have to write a function that takes in an object and a string literals array, and it returns the filtered object with the keys that appeared in the array of strings.
For example − If the object is {“a”: [], “b”: [], “c”:[], “d”: []} and the array is [“a”, “d”] then the output should be −
{“a”: [], “d”:[]}
Therefore, let’s write the code for this function,
We will iterate over the keys of the object whether it exists in the array, if it does, if shove that key value pair into a new object, otherwise we keep iterating and return the new object at the end.
Example
const capitals = { "usa": "Washington DC", "uk": "London", "india": "New Delhi", "italy": "rome", "japan": "tokyo", "germany": "berlin", "china": "shanghai", "spain": "madrid", "france": "paris", "portugal": "lisbon" }; const countries = ["uk", "india", "germany", "china", "france"]; const filterObject = (obj, arr) => { const newObj = {}; for(key in obj){ if(arr.includes(key)){ newObj[key] = obj[key]; }; }; return newObj; }; console.log(filterObject(capitals, countries));
Output
The output in the console will be −
{ uk: 'London', india: 'New Delhi', germany: 'berlin', china: 'shanghai', france: 'paris' }
- Related Articles
- Filter an object based on an array JavaScript
- What are the properties of an array object in JavaScript?
- How to filter object array based on attributes in jQuery?
- Create an object based on 2 others in JavaScript
- Sort object array based on another array of keys - JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- Manipulate Object to group based on Array Object List in JavaScript
- Remove number properties from an object JavaScript
- Extract properties from an object in JavaScript
- MongoDB aggregation to sum individual properties on an object in an array across documents
- Best way to flatten an object with array properties into one array JavaScript
- Filter array based on another array in JavaScript
- Get the Component Type of an Array Object in Java
- How to remove an object using filter() in JavaScript?
- How to filter documents based on an array in MongoDB?

Advertisements