- 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 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' }
Advertisements