

- 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 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 Questions & Answers
- Filter an object based on an array JavaScript
- What are the properties of an array object in JavaScript?
- Create an object based on 2 others in JavaScript
- How to filter object array based on attributes in jQuery?
- Remove number properties from an object JavaScript
- Extract properties from an object in JavaScript
- Sort object array based on another array of keys - JavaScript
- Manipulate Object to group based on Array Object List in JavaScript
- Get the Component Type of an Array Object in Java
- Query on the last object of an array with MongoDB
- MongoDB aggregation to sum individual properties on an object in an array across documents
- How to get the length of an object in JavaScript?
- How to get the values of an object in JavaScript?
- Filter an array containing objects based on another array containing objects in JavaScript
- JavaScript Object Properties
Advertisements