简体   繁体   中英

How do I Sort the data returned in JSON format by an AJAX request?

I have an AJAX request against a sharepoint API. It returns an array of Files. I am taking these resulting array and adding a series of options to a Select element. I would like to be able to sort the array alphabetically by the Name property. How would I go about doing this? MY current Ajax call is below.Thank you

    jQuery.ajax({
        url: url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            jQuery("#items").empty();
            jQuery("#items").prepend('<option value="-1">-Select Item-</option>').val('-1');
            jQuery.each(data.d.results, function (index, item) {
                jQuery("#items").append('<option value="' + item.ServerRelativeUrl + '">' + item.Name + '</option>');
            });
            jQuery("#items").val("");
        },
        error: function () {
            alert("Error getItems");
        }
    });
};

You could sort the array in javascript, but can't you get Sharepoint to return an ordered list for you? Seems like that'd be a useful feature. Anyway, in javascript:

jQuery("#items").prepend('<option value="-1">-Select Item-</option>').val('-1');
var res = data.d.results.sort(function(a,b){
    if(a.Name < b.Name) return -1;
    if(a.Name > b.Name) return 1;
    return 0;
});
jQuery.each(res, function (index, item) {
    jQuery("#items").append('<option value="' + item.ServerRelativeUrl + '">' + item.Name + '</option>');
});

If i were you i would use somthing like underscore

http://underscorejs.org/#sortBy

somthing like this

var array = [
    { name: "banana" },
    { name: "carrot" },
    { name: "apple" }
];

var sorted = _.sortBy(array,"name");

and pass the data.d.results in the array

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM