How to sort a Javascript object, or convert it to an array?

前端 未结 7 585
囚心锁ツ
囚心锁ツ 2020-12-13 04:13

I have some JSON data that I get from a server. In my JavaScript, I want to do some sorting on it. I think the sort() function will do what I want.

However, it seems

7条回答
  •  一个人的身影
    2020-12-13 04:47

    I wrote a small function to recursively convert an object with properties that may also be objects to a multi-dimensional array. This code is dependent on underscore or lodash for the forEach and toArray methods.

    function deepToArray(obj) {
        var copy = [];
    
    
        var i = 0;
        if (obj.constructor == Object ||
            obj.constructor == Array) {
    
            _.forEach(obj, process);
    
        } else {
    
            copy = obj;
    
        }
    
    
        function process(current, index, collection) {
    
            var processed = null;
            if (current.constructor != Object &&
                current.constructor != Array) {
                processed = current;
            } else {
                processed = deepToArray(_.toArray(current));
            }
    
            copy.push(processed);
    
        }
    
        return copy;
    }
    

    Here is the fiddle: http://jsfiddle.net/gGT2D/

    Note: This was written to convert an object that was originally an array back into an array, so any non-array index key values will be lost.

提交回复
热议问题