Computer >> Computer tutorials >  >> Programming >> Javascript

How to access nested json objects in JavaScript?


Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object.

In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.

Example-1

<html>
<body>
<script>
   var person = {
      "name":"Ram",
      "age":27,
      "vehicles": {
         "car":"limousine",
         "bike":"ktm-duke",
         "plane":"lufthansa"
      }
   }
   document.write("Mr Ram has a car called" + " " + person.vehicles.car);
</script>
</body>
</html>

Output

Mr Ram has a car called limousine

Example-2

In the following example, an object called "air-lines" is doubly nested (nested inside a nested object). The property of that doubly nested object(lufthansa) is accessed through dot notation as shown below.

<html>
<body>
<script>
   var person = {
      "name":"Ram",
      "age":27,
      "vehicles": {
         "car":"limousine",
         "bike":"ktm-duke",
         "airlines":{
            "lufthansa" : "Air123",
             "British airways" : "Brt707"
         }
      }
   }
   document.write("Mr Ram travels by plane called" + " " + person.vehicles.airlines.lufthanza);
</script>
</body>
</html>

Output

Mr Ram travels by plane called Air123