一个面试题,使用 js 递归 实现 walk 函数,将树结构的数据转化为列表数据

2020-10-14 18:28发布

一个面试题,使用 js 递归
实现 walk 函数,将树结构的数据转化为列表数据

/**
input: [{
	id: 1,
	text: 'text1',
	children: [{
		id: 2,
		text: 'text2',
		parentId: 1,
		children: [{
			id: 4,
			text: 'text4',
			parentId: 2
		}]
	}, {
		id: 3,
		text: 'text3',
		parentId: 1
	}]
}]
output: [{
	id: 4,
	text: 'text4',
	parentId: 2
}, {
	id: 2,
	text: 'text2',
	parentId: 1
}, {
	id: 3,
	text: 'text3',
	parentId: 1
}, {
	id: 1,
	text: 'text1'
}, ];
**/
function walk(list) {
// code here
}

1条回答
虎瘦雄心在
2楼-- · 2020-10-14 18:58
var input = [{
    id: 1,
    text: 'text1',
    children: [{
        id: 2,
        text: 'text2',
        parentId: 1,
        children: [{
            id: 4,
            text: 'text4',
            parentId: 2
        }]
    }, {
        id: 3,
        text: 'text3',
        parentId: 1
    }]
}];

var output = [];
(function walk(list) {
    list.forEach(function (item) {
        if (item.children) {
            walk(item.children);
            delete item.children;
        }
        output.push(item);
    })
}(input));
console.log(output);
查看更多
登录 后发表回答