Adding a sub key element to existing javascript object Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Adding a sub key element to existing javascript object without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Adding a sub key element to existing javascript object - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji