我正在尝试使用lodash显示我拥有的JSON的所有值,就我所知,它最适合这种情况,如您所见,json很深,某些类别为空,这对我来说更具挑战性,我想知道哪个函数最适合显示这样的非结构化和深层JSON.是foreach还是filter? Lodash是这里最好的选择吗?数据最终将显示在react应用程序中,但现在我正在尝试进行映射/ foreach /过滤器或可以动态遍历所有项目的任何内容.
预期的输出是列表项嵌套树. >
{
"name": "Menu","children": [
{
"type": "category","name": "Burgers","children": [
{
"type": "item","name": "Burger 1","children": [
{
"type": "modifier","name": "Promo","children": [
{
"type": "item","name": "Promo 1"
}
]
},{
"type": "group","name": "Drinks","name": "Coke"
},{
"type": "item","name": "Light Coke"
},"name": "Sprite"
},"name": "Fanta"
}
]
},{
"type": "modifier","name": "Without","children": [
{
"type": "ingredient","name": "Onion"
},{
"type": "ingredient","name": "Tomato"
},"name": "Pickles"
}
]
}
]
},{
"type": "item","name": "Burger 2","name": "Coming Soon Offers"
}
]
},{
"type": "category","name": "Pizzas","name": "Pizza 1","name": "Mashrooms"
},"name": "Olives"
}
]
}
]
},"name": "Pizza 2","name": "Olives"
}
]
}
]
}
]
}
]
}
@H_301_11@
最佳答案@H_301_11@
只要您处理了未知深度的数据,就应该使用递归.
let obj = {
"name": "Menu","name": "Olives"
}
]
}
]
}
]
}
]
}
let body = document.querySelector('body');
function print(obj){
let str = `<li>${obj.name}</li>`;
if(obj.children){
str += '<ul>'
for(let c of obj.children) str += print(c)
str += '</ul>'
}
return str;
}
document.body.innerHTML = print(obj);
@H_301_11@