0

次の形式の JSON オブジェクトがあります。

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

ネストされたオブジェクトの各レベルを位置属性でソートしようとしています。オブジェクトを再帰的に繰り返すことはできますが、並べ替えをどこから始めればよいかわかりません...

4

1 に答える 1

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;
于 2012-04-27T22:42:16.537 に答える