Searching objects by value in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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']
raja
Published on 31-Aug-2020 06:42:37
Advertisements