Get value from JSON object in JavaScript dynamically | Code

  • by

You Get value from JSON object in JavaScript dynamically using array-like syntax. Just parse JSON (if not JSON object) value and use loop to get each value and keys present in JSON object.

Get value from JSON object in JavaScript dynamically

Simple example code with different data.

<!DOCTYPE html>
<html>
<head>

  <script>

    var response = '{"1":10,"2":10}';
    var r = JSON.parse(response);

    for(key in r)
    {
      var val =r[key];

      console.log(key,val)
    }
  </script>

</head>
</html>

Output:

Get value from JSON object in JavaScript dynamically

You can also use Object.keys to obtain the array of the keys which you can use them to access the value by [ ] operator. It will each key-value pair of your object,

<script>

    var response = '{"1":10,"2":10}';
    var obj = JSON.parse(response);

    Object.keys(obj).forEach(function(key){
      var value = obj[key];
      console.log(key + ':' + value);
    });

</script>

Use for each loop for

var jsonData = {
    data: [{
        "key1": 1,
        "key2": 2
    }, {
        "key1": 3,
        "key2": 4
    }]
}
for (var index in jsonData.data) {
    for (var key in jsonData.data[index]) {
        console.log(key)
    }
}

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

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.