Adding a sub key element to existing javascript object

Original Object

var myObject = {
      name: "John Doe",
      state: "Washington DC"
}

I’m trying to add a sub object to the state key

myObject.state.county = "Frederick" 

This is not working and I would love some help. Ideally the end result would look something like this.

var myObject = {
      name: "John Doe",
      state: "Washington DC" {
            county: "Frederick"
      }
};

Answer

state is a string in your object, which doesn’t support adding newer properties to it. That’s why you will face an error.

You need to create an object to do that. bjects are the collection of key-value pairs and can have any number of properties attached to them. So, if you had your object like this:

var myObject = {
      name: "John Doe",
      state: {
            name: "Washington DC"
      }
};

Then a statement like this:

myObject.state.county = "Frederick";

will becomes valid, and will actually assign county to the state. Ready to learn more? Refer to this guide from Mozilla, which will take you through the JavaScript objects.

Leave a Reply

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