Accessing nested objects in JavaScript

 Accessing nested objects in JavaScript

When you are using JavaScript you will constantly be dealing with nested objects. The nested object maybe an array, or a regular object within the object. 

Let's look at some of the examples on how to use nested objects. In the first part of the script we are accessing the color of Jims car and storing it in colorOfJimsFord variable.This seems straight forward using object notation. This is part of vechiles object.

In the second instance, we are accessing the object called as user which is defined as a constant. You can see how we use the dot notation to access the inner most and outer values. 

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Accessing nested objects</title>
    <div id="res"></div>
        var res = document.getElementById("res");

        vehicles = {
        "Jim's Ford Focus": { "color": "white""isDamaged": true"wheels": 4 },
        "Bob's Suzuki Swift": { "color": "green""isDamaged": false"wheels": 4 },
        "Alex's Harley Davidson": { "color": "black""isDamaged": false"wheels": 2 }
        const user = {
                id: 101,
                email: '',
                personalInfo: {
                    name: 'Jack',
                    address: {
                        line1: 'westwish st',
                        line2: 'washmasher',
                        city: 'wallas',
                        state: 'WX'
        var colorOfJimsFord = vehicles["Jim's Ford Focus"]["color"];
        res.innerText = colorOfJimsFord;
        const name =;
        const userCity =;
        res.innerText += "\n" + name + " stays in " + userCity;

Post a Comment