Reverse object in jQuery.each

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

HTML:



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

    jsonObj = [];

                $.each(data.reverse(), function (i, dt) {
                    jsonObj.push({
                        'id': dt.id
                    });
    
    0 讨论(0)
  • 2021-01-04 09:51

    Here's an option that seemed to have worked for me. Hope this helps someone. Obviously only works on simple objects (non-nested) but I suppose you could figure out way to make something more complicated with a little extra work.

    var reversed_object = {};
    Object.keys(original_object).reverse().forEach(function(key)
    { reversed_object[key] = original_object[key]; });
    
    0 讨论(0)
  • 2021-01-04 09:53

    You can use javascript function sort() or reverse()

    var data = $.parseJSON($('#sdata').val());
    data.reverse();
    $.each(data, function(id, sc) {
    alert(id);
    }
    
    0 讨论(0)
  • 2021-01-04 09:59

    There is another solution, a fairly easy one:

    $(yourobject).toArray().reverse();
    

    That's it.

    0 讨论(0)
  • 2021-01-04 10:03

    As it is, you can't in any reliable manner. Because you are enumerating an Object, there is never a guaranteed order.

    If you want a guaranteed numeric order, you would need to use an Array, and iterate backwards.


    EDIT: This will convert your Object to an Array, and do a reverse iteration.

    Note that it will only work if all the properties are numeric.

    var data = $.parseJSON($('#sdata').val());
    var arr = [];
    
    for( var name in data ) {
        arr[name] = data[name];
    }
    var len = arr.length;
    while( len-- ) {
        if( arr[len] !== undefined ) {
            console.log(len,arr[len]);
        }
    }
    
    0 讨论(0)
  • 2021-01-04 10:07

    For Objects

    If you are dealing with an object, reverse() won't work! Instead you can do this to maintain the order.

    $.each(Object.keys(myObj).reverse(),function(i,key){
      var value = myObj[key];
      //you have got your key and value in a loop that respects the order, go rock!
    });
    
    0 讨论(0)
提交回复
热议问题