Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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']
Advertisements