0

I have the following object structure:

var obj = {
    "51523":{
        "firstname":"Tiki",
        "lastname":"Pur",
        "age":25
    },
    "98741":{
        "firstname":"Nagasti",
        "lastname":"Bagamba",
        "age":20
    }
}

First - the reason behind this structure. I want to be able to access objects inside obj easily, like so:

obj["51523"].age = 25

is there a way of adding a new object to obj?

1
  • 2
    sure, obj["11111"]= {} Commented Oct 23, 2015 at 19:12

3 Answers 3

1

Yes, use dot or bracket notation... obj.newObj = {} or obj['12345'] = {}

Dot Notation

obj.newObject = {
    "firstname": "John",
    "lastname": "Smith",
    "age": 30
}

Bracket Notation

obj['12345'] = {
    "firstname": "John",
    "lastname": "Smith",
    "age": 30
}
Sign up to request clarification or add additional context in comments.

2 Comments

or using bracket notation like @juvian stated
indeed, thanks guys.I was close to solve this alone hehe.
0

Yes, It can be done in several ways

1) Obj["newobj"]={"key":"value"}

2) Obj.newObj = {"key":"value"}

you can use Constructor function if you want to create multiple objects or can use Object.create() and add to existing object using 1 or 2

Comments

0

You need to define obj as a variable and use dot notation to set properties equal to objects.

Example:

 var example = true;
 example.tutorialProperty = {
      aProperty: null,
      aBoolean: true,
      anInteger: 1
 }

If you wanted to cycle through them, then you could make a property that contains multiple variable objects.

 var example = true;
 var object_one = {
      property: true
 }
 var object_infinity = {
      property: true
 }
 example.objectArray = [object_one, object_infinity];

Now example has a property with the value of an array.

There's other ways to do this, but this should do for now.

Hope I helped!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.