Filtering of JavaScript object

JavascriptWeb DevelopmentObject Oriented Programming

Here we need to create a function that takes in an object and a search string and filters the object keys that start with the search string and returns the object

Here is the code for doing so −


const obj = {
   "PHY": "Physics",
   "MAT": "Mathematics",
   "BIO": "Biology",
   "COM": "Computer Science",
   "SST": "Social Studies",
   "SAN": "Sanskrit",
   "ENG": "English",
   "HIN": "Hindi",
   "ESP": "Spanish",
   "BST": "Business Studies",
   "ECO": "Economics",
   "CHE": "Chemistry",
   "HIS": "History"
const str = 'en';
const returnFilteredObject = (obj, str) => {
   const filteredObj = {};
   Object.keys(obj).forEach(key => {
      if(key.substr(0, str.length).toLowerCase() ===
         filteredObj[key] = obj[key];
   return filteredObj;
console.log(returnFilteredObject(obj, str));

Code explanation −

We simply iterate over each key of the object, if it starts with the str we received as argument, then we save it in another object otherwise we keep on iterating.

For the purpose of this very problem, we iterated through each key and shoved the required key in a new object, but for a more performant solution instead of creating a new object we could have just deleted the unwanted properties from the original object.


Output in the console will be −

Published on 18-Aug-2020 10:50:50