How can I add a key/value pair to a JavaScript object?

Here is my object literal:

var obj = 
key1: value1, key2: value2

How can I add

key3: value3
to the object?

Text Copied From
on : Wed, Jul 22, 2009 Views : 1285035

Accepted Answer

There are two ways to add new properties to an object:

var obj = 

  key1: value1,
  key2: value2 

Using dot notation:

obj.key3 = value3;

Using square bracket notation:

obj[key3] = value3;

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = 
function (propertyName) 

  return obj[propertyName];

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();
Text Copied From
on : Wed, Jul 22, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp