Reverse object in jQuery.each

后端 未结 9 639
清歌不尽
清歌不尽 2021-01-04 09:25

HTML:



        
相关标签:
9条回答
  • 2021-01-04 10:10

    I don't know, but for the simple stuff I work with, this function does the job. It doesn't rely on numeric keys. And will flip simple objects top to bottom. I don't understand complex Objects, so I don't know how "robust" it is.

    function flipObject(obj){
        var arr = [];
        $.each(obj, function(key, val){
            var temp = new Object;
            temp['key'] = key;
            temp['val'] = val;
            arr.push(temp);
            delete temp;
            delete obj[key];
        });
        arr.reverse();
        $.each(arr, function(key, val){
            obj[val['key']] = val['val'];
        });
    }
    
    0 讨论(0)
  • 2021-01-04 10:11

    If all you need to do is generate some HTML out of your JSON and put generated elements into a container in reverse order you can use jQuery's prependTo method when building your HTML.

    var container = $('<div />');
    $.each(data, function (key, value) {
        $('<div>' + value + '</div>').prependTo(container);
    });
    
    0 讨论(0)
  • I tried this and it worked perfectly for me.

    var data = $.parseJSON($('#sdata').val());
    $.each(data.reverse(), function(id, sc) {
        alert(id);
    });
    

    The only change is the "reverse()" in line 2.

    0 讨论(0)
提交回复
热议问题