次のような JSON オブジェクトがあります。
{
"name":"Me",
"groups": [
{
"name":"My Garage",
"groups":[
{
"name":"My Cars",
"groups":[],
"tags":[
{
"name":"Fiet Punto"
},
{
"name":"Gallardo"
}
]
},
{
"name":"My Bikes",
"groups":[]
}
]
},
{
"name":"My Bank",
"groups":[
{
"name":"Swiss Bank",
"groups":[]
},
{
"name":"Bank of America",
"groups":[],
"tags":[
{
"name":"Account 1"
},
{
"name":"Account 2"
}
]
}
]
}
],
"tags":[
{
"name":"My tag 1"
},
{
"name":"My tag 2"
}
]
}
私の望ましい出力は次のとおりです。
Me
--My Garage
--My Cars
--Fiet Punto
--Gallardo
--My Bikes
--My Bank
--Swiss Bank
--Bank of America
-- Account 1
-- Account 2
--My Tag 1
--My Tag 2
再帰の構築に問題があります。私がやりたいことは次のとおりです。
- ルート オブジェクトを取得します。
- を印刷し
name
ます。 groups
オブジェクト内に存在するかどうかを検索tags
します。- それらのいずれかが存在する場合は、内側のオブジェクトをループします。
- 正しいインデントを適用し、内側のオブジェクトに対して上記の手順に従います。
どうすればこれを達成できますか?
編集 :
function getAllGroups(jsonObject)
{
//print the name of the current level object.
$("body").append(jsonObject.name);
//now if this object contains groups
if( jsonObject.hasOwnProperty( 'groups' ) )
{
//and if it is an array
if( jsonObject.groups.length > 0 )
{
//then for each object in groups of this object, call the function again.
$(jsonObject.groups).each(function(i, innerObject){
//print the index for debugging.
console.log(i + innerObject.name);
//make a recursive call to the function.
getAllGroups(innerObject);
});
}
}
else
{
console.log("does not exist anymore.")
}
}
tags
と の両方をgroups
並行して評価し、レベルを維持しながら名前を出力する方法がわかりません。
より正確には、ツリーのレベルを取得する方法がわかりません。