JS将普通对象数组转为树形结构

文章介绍了如何将包含parent_id的数组转换为树形结构的两种JavaScript实现方法:一种是通过双重循环遍历,另一种是使用reduce函数。两种方法都旨在构建一个嵌套结构,其中每个节点包含其子节点,如果子节点不存在,则表示为空的children数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原始数据

const arr = [
	{ id: 1, name: '泡泡哥', age: 18 },
	{ id: 4, name: '瓜瓜龙', age: 22, parent_id: 1 },
    { id: 2, name: '胡老板', age: 16 },
    { id: 5, name: '小肥兔', age: 20, parent_id: 4 },
    { id: 3, name: '鸡鸡爆', age: 32, parent_id: 1 },
    { id: 6, name: '哈撒K', age: 99 }
]

期望数据

[
	{
		id: 1,
		name: '泡泡哥',
		age: 18,
		children: [
			{
 				id: 4,
				name: '瓜瓜龙',
   				age: 22,
                parent_id: 1,
                children: [
					{
                    	id: 5,
                        name: '小肥兔',
                        age: 20,
                        parent_id: 4,
                        children: [] // 方法一中如果children为空数组,那么不会显示
   					}
				]
			},
            {
				id: 3,
                name: '鸡鸡爆',
                age: 32,
                parent_id: 1,
                children: [] // 方法一中如果children为空数组,那么不会显示
 			}
		]
	},
	{
		id: 2,
        name: '胡老板',
        age: 16,
        children: [] // 方法一中如果children为空数组,那么不会显示
	},
    {
        id: 6,
        name: '哈撒K',
        age: 99,
        children: [] // 方法一中如果children为空数组,那么不会显示
	}
]

实现方法

方法一

通过双重循环遍历实现

/**
 * 数组转树形结构
 * @param {Array} obj 原始数组数组
 * @param {String} id parent_id对应的父级属性
 * @return {Array} 转换成树形结构的数据
 */
function formatTree(obj, id) {
    // 深拷贝原数据
    const copyedObj = JSON.parse(JSON.stringify(obj))
    return copyedObj.filter(parent => {
        const findChildren = copyedObj.filter(child => {
            if (parent[id] !== parent.parent_id) return parent[id] === child.parent_id
        })
        findChildren.length > 0 ? parent.children = findChildren : delete parent.children
        // 返回顶层,依据实际情况判断这里的返回值
        return parent.parent_id === 0 || parent.parent_id === null
    })
}

// 使用
const arrTree = formatTree(arr,'id')
console.log(arrTree)

方法二

使用 reduce

const arrTree = arr.reduce((prev, item, index, arr) => {
	item.children = arr.filter(val => val.parent_id === item.id)
	if (!item.parent_id) prev.push(item)
	return prev
}, [])
console.log(arrTree);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值