[英]JavaScript :: Iterate through nested JSON object and create new structure
嘗試將嵌套的JSON數據( data1
)重組為“適當的”格式( data2
),到目前為止沒有成功。
data1
是根據給定的查找html文件的父目錄(配方)生成的。
我要使用data1
來輸出data2
因為文件夾中的任何內容都比純嵌套對象更好地表示為對象數組。
var data1 = {
"cake": {
"chocolate": {
"black-forest": {
"name": "Black Forest",
"path": "recipes/cake/chocolate/black-forest.html"
},
"new-shortcake": {
"milk-chocolate-shortcake": {
"name": "Milk chocolate shortcake",
"path": "recipes/cake/chocolate/shortcake/milk-chocolate-shortcake.html"
},
"dark-chocolate-shortcake": {
"name": "Dark chocolate shortcake",
"path": "recipes/cake/chocolate/shortcake/dark-chocolate-shortcake.html"
}
}
}
},
"pasta": {
"spaghetti": {
"aglio-olio": {
"name": "Spagehetti Aglio Olio",
"path": "recipes/pasta/spaghetti/aglio-olio.html"
},
"carbonara": {
"name": "Carbonara",
"path": "recipes/pasta/spaghetti/carbonara.html"
}
},
"lasagna": {
"name": "Lasagna",
"path": "recipes/pasta/lasagna.html"
}
}
}
var data2 = [
{
"name": "cake",
"children": [
{
"name": "chocolate",
"children": [
{
"name": "Black Forest",
"path": "recipes/cake/chocolate/black-forest.html"
},
{
"name": "New Shortcake",
"children": [
{
"name": "Milk chocolate shortcake",
"path": "recipes/cake/chocolate/shortcake/milk-chocolate-shortcake. html"
},
{
"name": "Dark chocolate shortcake",
"path": "recipes/cake/chocolate/shortcake/dark-chocolate-shortcake. html"
}
]
}
]
}
]
},
{
"name": "pasta",
"children": [
{
"name": "spaghetti",
"children": [
{
"name": "Spagehetti Aglio Olio",
"path": "recipes/pasta/spaghetti/aglio-olio.html"
},
{
"name": "Carbonara",
"path": "recipes/pasta/spaghetti/carbonara.html"
}
]
},
{
"name": "Lasagna",
"path": "recipes/pasta/lasagna.html"
}
]
}
]
https://codepen.io/kyooriouskoala/pen/LLLXmG
任何幫助,不勝感激!
PS:最終目標是使用新的數據結構構建菜單。
我希望這個輸出是您的意思。
var final = [];
function tree(object, temp){
for(var key in object){
var folder = {};
if(object[key] !== null && typeof object[key] == 'object'){
//console.log(key);
if(_.has(object[key], "path")){
folder.name = object[key].name;
folder.path = object[key].path;
folder.children = [];
} else{
folder.name = key;
folder.children = object[key];
}
final.push(folder);
tree(object[key]);
}
}
return final;
}
這會將您的數據輸出為具有所需值的關聯對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.