user1022241
user1022241

Reputation:

Sort complex JSON based on particular key

I have a JSON object with the following format:

{
    items:{
        nestedObj:{
            position:3
        },
        nestedObj2:{
            position:1
        },
        nestedObj3:{
            position:2,
            items:{
                dblNestedObj:{
                    position:2
                },
                dblNestedObj2:{
                    position:3
                },
                dblNestedObj3:{
                    position:1
                }
            }
        }
    }
}

I am attempting to sort each level of nested object by their position attribute. I can recursively iterate the object, but I don't know where to start for sorting it...

Upvotes: 0

Views: 527

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Unfortunately it's not quite so easy to use the sort method as it would if you had an array. So let's build an array:

var tmp = [], x;
for( x in obj.items) { // assuming your main object is called obj
    tmp.push([x,obj.items[x].position]);
    // here we add a pair to the array, holding the key and the value
}

// now we can use sort()
tmp.sort(function(a,b) {return a[1]-b[1];}); // sort by the value

// and now apply the sort order to the object
var neworder = {}, l = tmp.length, i;
for( i=0; i<l; i++) neworder[tmp[i][0]] = obj.items[tmp[i][0]];
obj.items = neworder;

Upvotes: 1

Related Questions