Skip to content

JavaScript Nested object | Example code

  • by

JavaScript Nested objects are the objects that are inside another object. Dealing with nested objects often we’ll be needing to access the innermost nested values safely.

Nested object

const user = {
    id: 101,
    email: '[email protected]',
    personalInfo: {
        name: 'John',
        address: {
            line1: '101',
            line2: 'Stree Line',
            city: 'NY',
            state: 'WX'
        }
    }
}

Access the name of the user

const name = user.personalInfo.name;

You can access and modify nested object properties using dot notation or bracket notation, and you can even add new properties to nested objects.

JavaScript Nested object

Simple example code accessing nested json objects is just like accessing nested arrays

<!DOCTYPE html>
<html>
<body>

  <script>
   const user = {
    id: 101,
    email: '[email protected]',
    personalInfo: {
      name: 'John',
      address: {
        line1: '101',
        line2: 'Stree Line',
        city: 'NY',
        state: 'WX'
      }
    }
  }

  console.log(user)

</script>

</body>
</html> 

Output:

JavaScript Nested object

Arrays Within Objects

Now let’s look at an example of an object with an array as the value:

let instructorData = {
    name: "Tim",
    favoriteHobbies: ["Sailing", "Hiking", "Coding"]
};

Creating Nested Objects in JavaScript Dynamically

In ES6, Objects can be created with computed properties. To use a “dynamic” key, you have to use bracket notation:

Iterate through the elements of basis. Use the keys to find the corresponding element in nested, and use that as the key in the new object being created.

const basis = { a: '1', b: '2', c: '3', d: '4' };
const nested = { a: 'e', b: 'f', c: 'g', d: 'h', e: 'i', f: 'j', g: 'k' };

const result = Object.entries(basis).reduce((obj, [key, value]) => {
  obj[key] = [{
    [nested[key]]: value,
    date: Date.now()
  }];
  return obj;
}, {});

console.log(result);

Output:

{
  "a": [
    {
      "e": "1",
      "date": 1651208135047
    }
  ],
  "b": [
    {
      "f": "2",
      "date": 1651208135047
    }
  ],
  "c": [
    {
      "g": "3",
      "date": 1651208135047
    }
  ],
  "d": [
    {
      "h": "4",
      "date": 1651208135047
    }
  ]
}

How to create a nested object in JavaScript?

Answer: You can assign an object as a property value of another object.

const user = {
  name: "John Doe",
};

const address = {
  street: "123 Main Street",
  city: "New York",
  state: "NY",
  zipCode: "10001",
};

user.address = address;

Here’s an example of how you can create and work with nested objects in JavaScript:

// Creating a nested object
let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Exampleville",
    zipCode: "12345"
  }
};

// Accessing nested object properties
console.log(person.firstName);                  // Output: John
console.log(person.address.street);             // Output: 123 Main St

// Modifying nested object properties
person.address.city = "New Exampleville";
console.log(person.address.city);               // Output: New Exampleville

// Adding a new nested property
person.address.country = "USA";

// Iterating through nested object properties
for (let key in person) {
  if (typeof person[key] === "object") {
    for (let nestedKey in person[key]) {
      console.log(`${key}.${nestedKey}: ${person[key][nestedKey]}`);
    }
  } else {
    console.log(`${key}: ${person[key]}`);
  }
}

In this example, the person object has a nested address object. You can access properties within the nested object using dot notation (person.address.street) or bracket notation (person['address']['street']).

Do comment if you have any doubts or suggestions on this JS object 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