I have some array of objects, some objects can have some array again at any level, So I want all the objects in alphabetical order.
Ex:
{
"b": [
{
"pqr": [
{
"z": "s",
"t": "t"
}
],
"c": "d",
"q": "c"
},
{
"m": "h",
"b": "g"
}
]
}
I want the output as
{
"b": [
{
"c": "d",
"pqr": [
{
"t": "t",
"z": "s"
}
],
"q": "c"
},
{
"b": "g"
"m": "h",
}
]
}
after JSON.stringify()
, so basically I want the sorted order at any level, arrays can also have objects which also needs to be in sorted order, I have gone through other Stack Overflow questions, but did not find this.
I was trying using the below code (from https://stackoverflow.com/a/28565621/1364965, but this code does not solve my problem), but does not seem to work, recursion code does not seem to work,
function sortObject(obj) {
var tmpArr = [];
var tmpKeys = [];
if (obj instanceof Array) {
var objLen = obj.length;
for (var i = 0; i < objLen; i++) {
if (obj[i] instanceof Array) {
tmpArr[i] = sortObject(obj[i]);
} else {
for (key in obj[i]) {
tmpKeys.push(key);
}
tmpKeys.sort();
}
}
}
var temp = {};
var keys = [];
for (var key in obj) {
keys.push(key);
}
keys.sort();
for (var index in keys) {
temp[keys[index]] = sortObject(obj[keys[index]]);
}
return temp;
}
How it can be achieved?