0

EDIT 2

Check the fiddle - http://jsfiddle.net/SN5zT/2/

Following is the fiddle for which I am not sure why I am getting undefined in dropdown.

My fiddle - http://jsfiddle.net/z6GDj/

var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';


try {
    var sportPositionOptions = '';
    var parsedJson = JSON.parse(res);
    var allSportPosition = parsedJson.allSportPosition;
    var values = new Array();
    $.each(allSportPosition, function (index, value) {
        values[index] = value;
    });
    //alert(values.length);
    values.sort();
    $.each(values, function (atIndex, atValue) {
        sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
    });
    $(sportPositionOptions).appendTo("#player");

} catch (e) {
    alert("Parsing error:" + e);
}

$.each is automatically sorting keys to 25,26,27,28 for res.

Please explain the reason of this and why I am getting undefined ?

Let me know If i need to explain it more, I will surely do it :)

EDIT

Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/

Trialcoder
  • 5,816
  • 9
  • 44
  • 66
  • There is no notion of order in objects, they are sorted however the browser chooses to sort them. – adeneo Jan 09 '14 at 12:43
  • @adeneo Please explain this behavior http://jsfiddle.net/SN5zT/ as u can see it is getting sorted – Trialcoder Jan 09 '14 at 12:49
  • @Trialcoder: Check my answer. However, still trying find why your code wasn't working. – Dhanu Gurung Jan 09 '14 at 12:50
  • What you have is an object of objects, and there is no order in objects, if the browser chooses to order the object in a certain way when parsed, that's fine, but it's up to the browser, there is no standard that sets a specification for a certain sorting order on objects, they are by default unsorted as they are made up of named keys and values. – adeneo Jan 09 '14 at 12:51
  • You're expecting the object to be outputted in a certain order, and I'm not sure how to better explain this, but there is no order in objects. You can't expect the object to be iterated over in any given order, as there is no order. – adeneo Jan 09 '14 at 12:54
  • And as a sidenote, it's not jQuery or `$.each` that messes up the order of your object (that doesn't have order), it's `JSON.parse`, so the only option is to wrap the objects in an array, which has order, and not an object. – adeneo Jan 09 '14 at 12:58
  • @adeneo I just edited the fiddle so that I think we are on the same note http://jsfiddle.net/SN5zT/1/ – Trialcoder Jan 09 '14 at 13:00
  • 1
    We are on the same page, and the fiddle makes it even more clear. You're expecting to get the order in the dropdown that you have in the JSON string, but the JSON string is parsed into an object with objects, and ***there is no order in objects*** so you can't expect any order at all. – adeneo Jan 09 '14 at 13:08
  • 1
    And this is how it should be done -> http://jsfiddle.net/SN5zT/3/ – adeneo Jan 09 '14 at 13:13

5 Answers5

0

Try

values.push(value);

instead of

values[index] = value;

Fiddle Link

Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
0

$.each is doing the following assignment that is why you are getting so many undefined

values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"

During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys

vjy
  • 1,184
  • 1
  • 10
  • 24
0

Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Ceres
  • 3,524
  • 3
  • 18
  • 25
0

The following script is working, I also figured out where the "undefineds" came from.

http://jsfiddle.net/z6GDj/3/

var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';


try{
var sportPositionOptions = '';    
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
//    values[index] = value;
//});
//alert(values.length);

$.each(values,function(atIndex, atValue){       
    sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';            
});
$(sportPositionOptions).appendTo("#player");

}
catch(e){
    alert("Parsing error:"+ e); 
    }

The array is sorted automatically, because the keys are set correctly. see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold many values under a single name, and you can access the values by referring to an index number."

Or: Change the index, and you´re changing the order. (index indicates the order).

The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)

"Also note that you don't have to add in order and you can actually skip values, as in

myArray[myArray.length + 1000] = someValue;

In which case the values in between will have a value of undefined."

Community
  • 1
  • 1
Qullbrune
  • 1,925
  • 2
  • 20
  • 20
0

What you need to do is define your options before you sort them , and then append them to your select:

var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';


try {
    var sportPositionOptions = '',
        parsedJson = JSON.parse(res),
        allSportPosition = parsedJson.allSportPosition,
        options = new Array();

    $.each(allSportPosition, function (index, value) {
        options[index] = $('<option></option>', {
            value: index,
            text: value
        });
    });

    $.each(options, function (index) {
        $('#player').append(options[index]);
    });

} catch (e) {
    alert("Parsing error:" + e);
}

jsfiddle: http://jsfiddle.net/z6GDj/11/

Andy
  • 2,892
  • 2
  • 26
  • 33
  • 1
    Still losing index value. :) I checked it. Here http://jsfiddle.net/budhram/z6GDj/8 – Dhanu Gurung Jan 09 '14 at 13:10
  • You need to create your options in the array before you sort them, and then just append them to your select. Check my answer for example. – Andy Jan 09 '14 at 13:24