How to sort a JS object of objects?

后端 未结 5 1833
礼貌的吻别
礼貌的吻别 2020-12-18 03:03

I have built an object in PHP, used JSON_encode function and send it as a JSON string to my JS script via ajax. Then I convert it back to an object. The problem I am havin

5条回答
  •  一整个雨季
    2020-12-18 04:03

    I've changed Fabricio Matée answer to become more flexible and return the sorted object.

    function alphabetical_sort_object_of_objects(data, attr) {
        var arr = [];
        for (var prop in data) {
            if (data.hasOwnProperty(prop)) {
                var obj = {};
                obj[prop] = data[prop];
                obj.tempSortName = data[prop][attr].toLowerCase();
                arr.push(obj);
            }
        }
    
        arr.sort(function(a, b) {
            var at = a.tempSortName,
                bt = b.tempSortName;
            return at > bt ? 1 : ( at < bt ? -1 : 0 );
        });
    
        var result = [];
        for (var i=0, l=arr.length; i

    Then just call the function like this

    your_object = alphabetical_sort_object_of_objects(your_object, 'attribute_to_sort');
    

提交回复
热议问题