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