Reverse object in jQuery.each

后端 未结 9 636
清歌不尽
清歌不尽 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'];
        });
    }
    

提交回复
热议问题