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']
Updated on: 2020-08-31T06:43:17+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements