Wednesday, 14 August 2013

Array of objects

Javascript example demonstrates how to push objects into array

Okay,
 This sample code snippet for pushing objects into an array rather than put into a javascript map (not google map ,lol .... just kidding)
now create a class Car .. and push 3 car objects into an array

class Car=function(){
    this.name="";
    this.type="";
    this.color="";
    this.numberOfWheels;  
}

var car1=new Car();
car1.name="Swift";
car1.type="lmv";
car1.color="red";
car1.numberOfWheels=4;


var car2=new Car();
car2.name="TATA Safari";
car2.type="suv";
car2.color="black";
car2.numberOfWheels=4;


var car3=new Car();
car3.name="TATA 1210";
car3.type="Truck";
car3.color="white";
car3.numberOfWheels=6;

var carArray=[];

carArray.push(car1);
carArray.push(car2);
carArray.push(car3);

alert(JSON.stringify(carArray));


the output will be

[
    {"name":"Swift", "type":"lmv", "color":"red", "numberOfWheels":"4"},
    {"name":"TATA Safari", "type":"suv", "color":"black", "numberOfWheels":"4"},
    {"name":"TATA 1210", "type":"Truck", "color":"white", "numberOfWheels":"6"}
]
 














No comments:

Post a Comment