- 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
Searching objects by value in JavaScript
Suppose we have an object like this −
const obj = { "name": "Vivek Sharma", "occupation": "Software Engineer", "age": 23, "contacts": [{ "name": "Mukul Sharma", "occupation": "Software Engineer", "age": 31, }, { "name": "Jay Sharma", "occupation": "Software Engineer", "age": 27, }, { "name": "Rajan Sharma", "occupation": "Software Engineer", "age": 32, }] };
Here it is nested up to only one level, but the nesting can be deeper as well. We are required to write an Object function Object.prototype.keysOf() that takes in a value and returns an array of all the keys that have the value specified in the argument.
So, now let's write the code for this function −
Example
const obj = { "name": "Vivek Sharma", "occupation": "Software Engineer", "age": 23, "contacts": [{ "name": "Mukul Sharma", "occupation": "Software Engineer", "age": 31, }, { "name": "Jay Sharma", "occupation": "Software Engineer", "age": 27, }, { "name": "Rajan Sharma", "occupation": "Software Engineer", "age": 32, }] }; const keysOf = function(val, obj = this, res = []){ const keys = Object.keys(obj); for(let ind = 0; ind < keys.length; ind++){ if(obj[keys[ind]] === val){ res.push(keys[ind]); }else if(typeof obj[keys[ind]] === 'object' && !Array.isArray(obj[keys[ind]])){ keysOf(val, obj[keys[ind]], res); }; }; return res; }; Object.prototype.keysOf = keysOf; console.log(obj.keysOf(23));
Output
The output in the console will be −
['age']
- Related Articles
- Sort array of objects by string property value in JavaScript
- Sort array of objects by string property value - JavaScript
- Sorting an array objects by property having null value in JavaScript
- How to Sort object of objects by its key value JavaScript
- Group objects by property in JavaScript
- Join two objects by key in JavaScript
- Searching an element in Javascript Array
- Sorting objects by numeric values - JavaScript
- How to group objects based on a value in JavaScript?
- Find specific key value in array of objects using JavaScript
- Retrieve property value selectively from array of objects in JavaScript
- Sort Array of objects by two properties in JavaScript
- Grouping array nested value while comparing 2 objects - JavaScript
- Searching in a sorted 2-D array in JavaScript
- Filter array of objects whose properties contains a value in JavaScript

Advertisements