JavaScript - Find keys for the matched values as like query in SQL


Suppose, we have an object like this −

const obj = {"100":"Jaipur","101":"Delhi","102":"Raipur","104":"Goa"};

We are required to write a JavaScript function that takes in one such object as the first argument and a search query term as the second argument. Then our function should return all those key/value pairs whose value includes the search term provided to the function as the second argument.

We will simply iterate through the object, building the resulting object (if it matches the condition) as we move through and lastly return that object.

Example

The code for this will be −

const obj = {
   "100":"Jaipur",
   "101":"Delhi",
   "102":"Raipur",
   "104":"Goa"
};
const findByQuery = (obj, query) => {
   const keys = Object.keys(obj);
   const res = {};
   keys.forEach(key => {
      // case insensitive search
      if(obj[key].toLowerCase().includes(query.toLowerCase())){
         res[key] = obj[key]
      };
   });
   return res;
};
console.log(findByQuery(obj, 'Pur'));

Output

And the output in the console will be −

{ '100': 'Jaipur', '102': 'Raipur' }

Updated on: 21-Nov-2020

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements