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: 'abc@eyehunts.com',
    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: 'abc@eyehunts.com',
    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;

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

Your email address will not be published. Required fields are marked *