如果解析嵌套多层的JSON数据?
问题描述
var dataDemo = [
{name: "订单处理", level:1 ,children:[
{name: "所有订单", level:2},
{name: "待付款", level:2, children:[
{name: "锁定及撤销出库", level: 3}
]},
{name: "待发货", level:2, children:[
{name: "填写发货单", level: 3},
{name: "修改发货单", level: 3},
{name: "下载发货单", level: 3},
]},
{name: "待收货", level:2},
{name: "已收货", level:2},
]}
]
如上面贴上的json
数据,目前我写的只有三层,我现在的做法是写三个嵌套for去解析处理,假设数据超过三层的时候我该怎么写?嵌套写for
也很乱
参考答案
var dataDemo = [
{name: "订单处理", level:1 ,children:[
{name: "所有订单", level:2},
{name: "待付款", level:2, children:[
{name: "锁定及撤销出库", level: 3}
]},
{name: "待发货", level:2, children:[
{name: "填写发货单", level: 3},
{name: "修改发货单", level: 3},
{name: "下载发货单", level: 3},
]},
{name: "待收货", level:2},
{name: "已收货", level:2},
]}
]
let parse = arr => {
arr.forEach(item => {
// do some ...
console.log('item: ', item)
if (Array.isArray(item.children)) {
parse(item.children)
}
})
}
parse(dataDemo)