Skip to content

Get value from JSON object in JavaScript dynamically | Code

  • by

You Get value from JSON objects in JavaScript dynamically using array-like syntax. Just parse JSON (if not JSON object) value and use a loop to get each value and key present in a 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 keys’ array, you can use to access the value by the Bracket [ ] 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

Discover more from Tutorial

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

Continue reading