js 递归取出想要的数据。

``````        var obj = [
{
"id": 1,
"name": "大天使1",
"children": [{
"id": 2,
"name": "大天使2",
"children": [{
"id": 3,
"name": "大天使3",
"children": [{
"id": 4,
"name": "大天使4",
"children": []
}]
}]
}]
},
{
"id": 5,
"name": "大天使5",
"children": []
},
{
"id": 6,
"name": "大天使6",
"children": []
}
]``````

``````var obj = [
{"id": 1, "name": "大天使1"},
{"id": 2, "name": "大天使2"},
{"id": 3, "name": "大天使3"},
{"id": 4, "name": "大天使4"},
{"id": 5, "name": "大天使5"},
{"id": 6, "name": "大天使6"}
]``````

4 个回答
``````function collect(arr) {
var ret = [];
for (var i = 0; i < arr.length; ++i) {
var item = arr[i];
ret.push({ id: item.id, name: item.name });
if (item.children instanceof Array) {
ret.push.apply(ret, collect(item.children));
}
}
return ret;
}
console.dir(collect(obj));``````

function dataFetch(data){
var ans = [];
for(var i=0;i<data.length;i++){

``````if data[i].children.length !=0:
ans = ans.concat(dataFetch(data[i].children))
else:
ans.push({i.id, i.name})``````

}
return ans;
}

``````const res = [];
var recursion = function(data) {
for(let item of data) {
res.push({ id: item.id, name: item.name })
if (item.children.length > 0) {
recursion(item.children);
}
}
}
recursion(obj)``````

``````let flatList=(list=[],res=[])=>{
list.forEach(({children,...other})=>{
res.push(other);
flatList(children,res);
})
return res;
}
flatList(obj);``````

``````let flatList=(list=[])=>{
return list.flatMap(({children,...other})=>{
return [other].concat(flatList(children));
})
}
flatList(obj);``````

你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进