Sunday, October 28, 2012

How to convert a JSON object array in to a javascript object array

Lets assume that this as our JSON array
var jsonEmployeeArray = [
    {"firstname":"Tom", "lastname":"Hunter", "age":"25"}, 
    {"firstname":"Edward", "lastname":"Watson", "age":"30"}, 
    {"firstname":"William", "lastname":"Martin", "age":"45"}
  ];

Now lets create our javascript object so that it has the same properties

function EmployeeObject(firstname, lastname, age) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.age = age;
}

Following is our function which convert the JSON array in to the EmployeeObject array

function convert(jsonArray) {
  var jsEmployeeArray = new Array();//Define our javascript array like this
  for(var i = 0; i < jsonArray.length; i++) {
    var employee = jsonArray[i];//get i th element
    //Create jsObject of type EmployeeObject as below
    var jsObj = 
      new EmployeeObject(employee.firstname, employee.lastname, employee.age);
    jsEmployeeArray[i] = jsObj;//Add created javascript object in to javascript array
  }
  return jsEmployeeArray;
}

That is all. Now call the above 'convert' function as below and it will return you a javascript array.
convert(jsonEmployeeArray);

No comments:

Post a Comment