基于特定键对复杂JSON进行排序

时间:2012-04-27 22:35:04

标签: javascript json

我有一个JSON对象,格式如下:

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

我试图按位置属性对每个级别的嵌套对象进行排序。我可以递归迭代对象,但我不知道从哪里开始对它进行排序......

1 个答案:

答案 0 :(得分:1)

不幸的是,如果你有一个数组,使用sort方法并不是那么容易。那么让我们构建一个数组:

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;
相关问题