JavaScript根据子级id递归查找至顶级id的集合

278 阅读1分钟

1、代码

let recursionData = [
	{
		id: 1,
		name: "一级",
		children: [
			{
				id: 2,
				name: "二级-1",
				children: [
					{
						id: 7,
						name: "三级-1",
						children: [
							{
								id: 10,
								name: "四级-1",
							},
						],
					},
					{
						id: 8,
						name: "三级-2",
					},
				],
			},
			{
				id: 3,
				name: "二级-2",
				children: [
					{
						id: 5,
						name: "三级-3",
					},
					{
						id: 6,
						name: "三级-4",
					},
				],
			},
			{
				id: 4,
				name: "二级-3",
				children: [
					{
						id: 9,
						name: "三级-5",
						children: [
							{
								id: 11,
								name: "四级-2",
							},
						],
					},
				],
			},
		],
	},
];

function funRecursion(list, id) {
	for (let i in list) {
		if (list[i].id == id) {
			// return [list[i]];
			return [list[i].id];
		}

		if (list[i].children) {
			let node = funRecursion(list[i].children, id);
			if (node !== undefined) {
				// return node.concat(list[i]);
				return node.concat(list[i].id);
			}
		}
	}
};

console.log(funRecursion(recursionData, 10)); // [10, 7, 2, 1]
console.log(funRecursion(recursionData, 10).reverse()); // [1, 2, 7, 10]

2、相关链接

原文链接