js 数组扁平结构转树tree结构

待处理数据

var treeList = [
	{
		title: "一级1——二级1",
		parentName: "一级1",
		parentId: 1,
		id: 11,
	},
	{
		title: "一级1——二级1——三级1",
		parentName: "一级1——二级1",
		parentId: 11,
		id: 111,
	},
	{
		title: "一级1——二级1——三级2",
		parentName: "一级1——二级1",
		parentId: 11,
		id: 112,
	},
	{
		title: "一级1——二级1——三级3",
		parentName: "一级1——二级1",
		parentId: 11,
		id: 113,
	},
	{
		title: "一级1——二级2",
		parentName: "一级1",
		parentId: 1,
		id: 22,
	},
	{
		title: "一级1——二级2——三级1",
		parentName: "一级1——二级2",
		parentId: 22,
		id: 221,
	},
	{
		title: "一级1",
		parentName: "",
		parentId: 0,
		id: 1,
	},
	{
		title: "一级1——二级2——三级2",
		parentName: "一级1——二级2",
		parentId: 22,
		id: 222,
	},
	{
		title: "一级1——二级2——三级3",
		parentName: "一级1——二级2",
		parentId: 22,
		id: 223,
	},
	{
		title: "一级2——二级1",
		parentName: "一级2",
		parentId: 33,
		id: 331,
	},
	{
		title: "一级2——二级2",
		parentName: "一级2",
		parentId: 33,
		id: 332,
	},
	{
		title: "一级2——二级3",
		parentName: "一级2",
		parentId: 33,
		id: 333,
	},
	{
		title: "一级2",
		parentName: "",
		id: 33,
	},
];

处理后数据

在这里插入图片描述

第一种,对象下标唯一性

function getTree(data = [], idKey = "id", pidKey = "parentId", childrenKey = "children") {
	if (!Array.isArray(data)) return [];
	let arr = JSON.parse(JSON.stringify(data));
	let obj = {},
		treeArr = [];
	arr.forEach((item) => {
		// item[childrenKey] = []; // 给每个item添加children属性并赋值空数组,最后一级会存在children
		delete item[childrenKey];
		obj[item[idKey]] = item;
	});
	arr.forEach((item) => {
		let objItem = obj[item[pidKey]];
		if (objItem) {
			(obj[item[pidKey]][childrenKey] || (obj[item[pidKey]][childrenKey] = [])).push(item);
		} else {
			treeArr.push(item);
		}
	});
	console.log(treeArr);
	return treeArr;
}
getTree(treeList);

第二种,两层filter(第一层的filter的判断条件有问题,目前只适合数据第一级的parentId为假值)

function getData(array = [], idKey = "id", pidKey = "parentId", childrenKey = "children") {
	if (!Array.isArray(array)) return [];
	let arr = JSON.parse(JSON.stringify(array));
	let data = arr.filter((item) => {
		let children = arr.filter((e) => item[idKey] === e[pidKey]);
		// item[childrenKey] = children;  // 最后一级会存在空数组children
		if (children.length) item[childrenKey] = children; // 去掉最后一级的children
		return !item[pidKey];
	});
	console.log(data);
	return data;
}
getData(treeList);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值