March 27, 2015

How to create objects/associative array in Javascript?

We can create the simple object as follow, lets create the object to save student data such as name, marks

var stu_obj = {} ;
stu_obj.name = ‘Sam’;
stu_obj.marks = ‘85%’;
alert(stu_obj.name);
alert(stu_obj.marks);
or
var obj = {name:’Sam’, marks: ‘85%’};
alert(obj.name);
alert(obj.marks);

what if you have to add new attributes to this object, we can do as follow

obj.class=’10th’; or obj[‘class’]=’10th’;

But in coding we have to create the object with dynamic attributes

function addattribute(name,value) {
obj.[name]=value;
}

Leave a Reply