Javascript / jquery parsing json in the same order

I have the following json object.

var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; 

I am preparing a select element that parses the above json as follows.

 var selElem = $('<select>', {'name' : name, 'grp' : grp}); for(key in json1) selElem.append($('<option>', {value:key, text: json1 [key]})); 

but the created select element looks like this.

 <select> <option value="15">15</option> <option value="30">30</option> <option value="45">45</option> <option value="00">00</option> </select> 

The problem here is that the json1 object contains 00 as the 1st element, but in the select element it is finally created.

Any work or solution to this problem.

+4
source share
1 answer

If you want to keep order, use an array:

 var json1 = [{val:"00",txt:"00"}, {val:"15",txt:"15"}, {val:"30",txt:"30"}, {val:"45",txt:"45"}]; 

And encode it:

 var selElem = $('<select>', {'name' : name, 'grp' : grp}); for(var i=0;i<json1.length;(i+=1)){ selElem.append($('<option>', {value:json1[i].val, text: json1[i].txt})); } 

Check this jsfiddle

+6
source

All Articles