将数组的某个属性放在一个数组里面
const data = [{
name: '中国',
children: [{
name: '教第三节课',
},
{
name: '食谱',
children: [{
name: '大一',
children: [{
name: '晚上吃什么',
children: [{
name: '番茄牛肉'
},
{
name: '小酥肉'
}
]
},
{
name: '中午吃什么',
children: [{
name: '水煮鱼'
}]
},
]
}]
},
{
name: '遛弯儿啦',
children: null
}
]
},
{
name: '干活'
}
];
var names=[]
function getData(data){
for(var i in data){
this.names.push(data[i].name) //将第一层的那么保存出来,
if(data[i].children){ //如果有children层,则继续遍历
this.getData(data[i].children)
}
}
return this.names
}
console.log(getData(data))
数组扁平化处理
var arr = [1, 2, [3, 4, 5, [6, 7, 8],9],10];
function flatten(arr) {
var res = [];
arr.map(item => {
if (Array.isArray(item)) {
res = res.concat(flatten(item));
} else {
res.push(item);
}
});
return res;
}
console.log(flatten(arr))