Get value for key from nested JSON object in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

Suppose, we have a nested JSON object like this −

const obj = {
   "prop": [
      {
         "key": "FOO",
         "value": "Foo is wonderfull, foo is great"
      },
      {
         "key": "BAR",
         "value": "Bar is bad, really bad"
      }
   ]
};

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

Our function should then return the value for the "value" property to which that particular key property belongs.

Example

The code for this will be −

const obj = {
   "prop": [
      {
         "key": "FOO",
         "value": "Foo is wonderfull, foo is great"
      },
      {
         "key": "BAR",
         "value": "Bar is bad, really bad"
      }
   ]
};
const findByKey = (obj, key) => {
   const arr = obj['prop'];
   if(arr.length){
      const result = arr.filter(el => {
         return el['key'] === key;
      });
      if(result && result.length){
         return result[0].value;
      }
      else{
         return '';
      }
   }
}
console.log(findByKey(obj, 'BAR'));

Output

And the output in the console will be −

Bar is bad, really bad
raja
Published on 23-Nov-2020 09:57:08
Advertisements