Find specific key value in array of objects using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have a JSON object like this −

const obj = {
   "LAPTOP": [{
      "productId": "123"
   }],
   "DESKTOP": [{
      "productId": "456"
   }],
   "MOUSE": [{
      "productId": "789"
   }, {
      "productId": "012"
   }],
   "KEY-BOARD": [{
      "productId": "345"
   }]
};

We are required to write a JavaScript function that takes in one such object as the first argument, and a key value pair as the second argument.

The key value pair is basically nothing but an object like this −

const pair = {"productId": 456};

The function should then search the object for the key with specified "productId" and return that.

Example

The code for this will be −

const obj = {
   "LAPTOP": [{
      "productId": "123"
   }],
   "DESKTOP": [{
      "productId": "456"
   }],
   "MOUSE": [{
      "productId": "789"
   }, {
      "productId": "012"
   }],
   "KEY-BOARD": [{
      "productId": "345"
   }]
};
const searchByPair = (obj = {}, pair = {}) => {
   const toSearch = Object.values(pair)[0];
   let required = undefined;
   Object.keys(obj).forEach((key) => {
      if(obj[key].find((pid) => pid.productId === toSearch)){
         required = key;
      }
   });
   return required;
};
console.log(searchByPair(obj, {
   'productId': '123'
}));

Output

And the output in the console will be −

LAPTOP
raja
Published on 21-Nov-2020 10:11:43
Advertisements