Skip to content

JavaScript JSON get value by key | Example code

  • by

Use the array filter function to get the JSON value for the key in JavaScript.

Example JSON get value by key in JavaScript

Simple example code gets value for a key from nested JSON object in JavaScript.

<!DOCTYPE html>
<html>
<head>

  <script>

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

   const arr = obj['prop'];
   
   const result = arr.filter(el => {
    return el['key'] === "BAR";
   });

   console.log(result[0].value)
 </script>

</head>
</html>

Output:

JavaScript JSON get value by key

JavaScript function that takes in one such object as the first argument, and a key string as the second argument.

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'));

Do comment if you have any doubts or suggestions on this JS JSON code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading