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
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.