How To Push 2 Items To An Array
In this fiddle line 27 shows var doctors = [ new Doctor('Doc A','A1'), new Doctor('Doc B','A1'), new Doctor('Doc C','A3') ]; Here, Doc A, Doc B and Doc C are hard-c
Solution 1:
May be something like this?
var doctors = [];
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false ,
success: function (data) {
$.each(data.doctors, function(index, currPat) {
doctors.push[currPat.id,currPat.username];
});
}
});
Your end result should be like this:
doctors = [[id1,name1],[id2,name2], ...... [id10,name10]]
Or you can also use the format like this:
doctors.push({id:currPat.id,name:currPat.username});
Then your end result should be something like this:
doctors = [{id:id1,name:name1},{id:id2,name:name2},......,{id:id10,name:name10}]
*I personally prefer format 2
EDIT Use of JQuery, .map()
var doctors;
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false ,
success: function (data) {
doctors = $.map(function () {
return [data.id,data.username];}).get();
}
});
A slightly more short hand than the above mention.
Solution 2:
It looks like jQuery.map()
can do what you need...
success: function (data) {
doctors = $.map(data.doctors, function(doctor) {
new Doctor(doctor.id, doctor.username);
});
}
Solution 3:
consider your Doctor function looks like:
// Doctor constructor with name and username properties
var Doctor = function(nameParam, usernameParam){
this.name = nameParam;
this.username = usernameParam;
};
then on AJAX success function populate all received doctors like:
$.each(jsonStr.doctors, function(index, currPat) {
var doc = new Doctor(currPat.name,currPat.username);
doctors.push(doc);
});
alert(JSON.stringify(doctors));
working fiddle
Post a Comment for "How To Push 2 Items To An Array"