Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 Output
The output in the console will be −
['age']
Advertisements
