Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add to a JavaScript object [duplicate]

Possible Duplicate:
Adding members to an existing object

Lets say you have the following object:

var object = {
    name: "Shawn"
};

I want to know if there is a function so I can add a new "section" to this object.

Like this for example:

object.add('age',14);

To turn the above object to:

var object = {
    name: "Shawn",
    age: 14
}

If you ask, "What have I tried". My answer is: "Nothing, i wouldnt be asking if I knew how to do this". I think it should be possible to do. But I just don't know how I will do it.

I looked at w3schools and don't recall seeing a built in function for this. Thanks you.

like image 672
Shawn31313 Avatar asked Dec 05 '22 15:12

Shawn31313


1 Answers

You can add function properties and methods by using the dot operator .:

obj.age = 24;

This is also equivalent:

obj['age'] = 24;
like image 56
David G Avatar answered Dec 25 '22 09:12

David G