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

原始数据

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);

猜你喜欢

转载自blog.csdn.net/weixin_43417844/article/details/129935906