js 递归取出想要的数据。

maybe
  • 3
新手上路,请多包涵
        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"}
        ]

请问要如何递归处理?

回复
阅读 1.1k
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));
Chris
  • 2
新手上路,请多包涵

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)

image.png

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

另一种写法
image.png

let flatList=(list=[])=>{
    return list.flatMap(({children,...other})=>{
       return [other].concat(flatList(children));
    })
}
flatList(obj);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏