- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' }
- Related Articles
- Query for implementing MySQL LIKE as MySQL IN?
- MongoDB query to search for string like “@email” in the field values
- The Keys and values method in Javascript
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- MySQL query to SELECT rows with LIKE and create new column containing the matched string?
- Mapping values to keys JavaScript
- Fetch maximum value from a column with values as string numbers like Value440, Value345, etc. in SQL
- Fetching JavaScript keys by their values - JavaScript
- How to map keys to values for an individual field in a MySQL select query?
- MySQL query to fetch specific records matched from an array (comma separated values)
- Iterate through Object keys and manipulate the key values in JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- Split keys and values into separate objects - JavaScript
- MongoDB query to add matched key to list after query?
- Find keys with duplicate values in dictionary in Python

Advertisements