js递归-适用于获取多级菜单/导航等
var data = [ { name: "所有物品", children: [ { name: "水果", children: [{ name: "苹果", children: [{ name: '青苹果' }, { name: '红苹果' }] }] }, { name: '主食', children: [ { name: "米饭", children: [{ name: '北方米饭' }, { name: '南方米饭' }] } ] }, { name: '生活用品', children: [ { name: "电脑类", children: [{ name: '联想电脑' }, { name: '苹果电脑' }] }, { name: "工具类", children: [{ name: "锄头" }, { name: "锤子" }] }, { name: "生活用品", children: [{ name: "洗发水" }, { name: "沐浴露" }] } ] } ] } ] let nameItem = []; function getName(vals) { vals.forEach((item, index) => { if (item.children) { getName(item.children) } else { console.log(item.name) nameItem.push(item.name) console.log("这一层没有东西") } }) return nameItem; } let items = getName(data); console.log(items);//["青苹果", "红苹果", "北方米饭", "南方米饭", "联想电脑", "苹果电脑", "锄头", "锤子", "洗发水", "沐浴露"]