JavaScript递归实现数组扁平化(数组降维)

Posted web半晨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript递归实现数组扁平化(数组降维)相关的知识,希望对你有一定的参考价值。

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",
							,
						],
					,
				],
			,
		],
	,
],
arr = [];

function funRecursion(list) 
	for (let i in list) 
		arr.push(
			id: list[i].id,
			name: list[i].name,
		);

		if (list[i].children) 
			funRecursion(list[i].children);
		
	
	return arr;


console.log(funRecursion(recursionData));
// […, …, …, …, …, …, …, …, …, …, …]

console.log(arr.map((item) => item.id).sort((a, b) => a - b));
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

以上是关于JavaScript递归实现数组扁平化(数组降维)的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript实现树形扁平化(数组降维)

JavaScript实现扁平数组结构与JSON树形结构相互转换递归reducecontinuepushconcatfor of

JavaScript递归树形扁平数组笔试题reduceforEachconcat

-----js实现数组扁平化-----

JavaScript 扁平与树形数组数据的转换

5种方式实现数组扁平化