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

Updated on: 25-Aug-2020

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements