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"}
]
 














What is serialization ?
Serialization is a process of translating an object into a format, that can be stored in a file or memory and restructured later in the same or another environment. There are different types of serializations like JSON, XML etc..

Example :
 class Person
  {
   string name;
   int age;
   string address;
 }

suppose there are 3 objects of class person .. p1, p2 and p3
now serialize these object into Json

{
"p1":{
        "name":"Rabi",
        "age":"23",
        "address":"Kolkata"
     }  ,


"p2":{
        "name":"Suman",
        "age" : "26",
        "address" : "Delhi"
     }  ,


"p3":{
        "name":"kumar",
        "age": "30",
        "address" : "Mumbai"
     }
}


Create Json using javascript

var Person=function(){
   this.name="";
   this.age;
   this.address="";
}

var p1=new Person();
p1.name="Rabi";
p1.age=23;
p1.address="Kolkata";



var p2=new Person();
p2.name="Suman";
p2.age=26;
p2.address="Delhi";


var p3=new Person();
p3.name="Kumar";
p3.age=30;
p3.address="Mumbai";

var personMap={};
personMap ["p1"] = p1 ;   personMap ["p2"] = p2 ;   personMap ["p3"] = p3 ;

alert(   JSON.stringify (personMap)   ); // convert the personMap object into string

What is JSON ?
Its JavaScript Object Notation