Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

树形结构转成列表 #40

Open
Sunny-117 opened this issue Nov 3, 2022 · 16 comments
Open

树形结构转成列表 #40

Sunny-117 opened this issue Nov 3, 2022 · 16 comments

Comments

@Sunny-117
Copy link
Owner

const data = [
    {
        id: 1,
        text: '节点1',
        parentId: 0,
        children: [
            {
                id: 2,
                text: '节点1_1',
                parentId: 1
            }
        ]
    }
]
function treeToList(data) {
    let res = [];
    const dfs = (tree) => {
        tree.forEach((item) => {
            if (item.children) {
                dfs(item.children);
                delete item.children;
            }
            res.push(item);
        });
    };
    dfs(data);
    return res;
}
@fencer-yd
Copy link

const  data = [
  {
    id: '1',
    name: '父节点1',
    children: [
      {
        id: '1-1',
        name: '子节点1-1',
        children: [
          {
            id: '1-1-1',
            name: '子节点1-1-1'
          },
          {
            id: '1-1-2',
            name: '子节点1-1-2'
          }
        ]
      }
    ]
  },
  {
    id: '2',
    name: '父节点2',
    children: [
      {
        id: '2-1',
        name: '子节点2-1'
      }
    ]
  }
]
const result = data.reduce(function (acc, cur) {
  acc.push({
    id: cur.id,
    name: cur.name,
    parentId: cur.parentId
  });
  cur.children && cur.children.forEach(child => {
    child.parentId = cur.id;
    arguments.callee(acc, child);
  })
  return acc;
}, []);

@Leadgq
Copy link

Leadgq commented Jan 12, 2023

// 我更喜欢这种,因为在真是业务场景中,应该保留原始解构
// 只是把深层的children拿出来放到第一层 个人想法
function treeToList(data) {
if (!Array.isArray(data) && data.length === 0) return;
// 方式1
return data.reduce((prev, cur) => {
const {children} = cur;
return Array.isArray(children) && children.length > 0 ? prev.concat(treeToList(children), cur) : prev.concat(cur);
}, [])
//方式2
return data.reduce((prev, cur) => {
const {children} = cur;
return [
...prev,
{...cur},
...(Array.isArray(children) && children.length > 0 ? treeToList(children) : [])
]
}, [])
}

@veneno-o
Copy link
Contributor

interface DataItem {
	id: number;
	text: string;
	parentId: number;
	children?: DataItem[];
}

function treeToList(data: DataItem[]) {
	const res: DataItem[] = [];
	for (const item of data) {
		dfs(item, res);
	}
    /**
     * 该函数用于深度遍历第一个参数tree, 并格式化收集到第二个参数res
     * @param tree 
     * @param res 
     */
	function dfs(tree: DataItem, res: DataItem[]): void {
		const newTree = {
			id: tree.id,
			text: tree.text,
			parentId: tree.parentId,
		};
		res.push(newTree);

		if (tree.children) {
			for (const item of tree.children) {
				dfs(item, res);
			}
		}
	}
	return res;
}

@litt1esea
Copy link

const data = [
    {
        id: '1',
        name: '父节点1',
        children: [
            {
                id: '1-1',
                name: '子节点1-1',
                children: [
                    {
                        id: '1-1-1',
                        name: '子节点1-1-1'
                    },
                    {
                        id: '1-1-2',
                        name: '子节点1-1-2'
                    }
                ]
            }
        ]
    },
    {
        id: '2',
        name: '父节点2',
        children: [
            {
                id: '2-1',
                name: '子节点2-1'
            }
        ]
    }
]




function tree2list(treeList) {

    const list = []

    const traverse = (treeNode, callback) => {
        const queue = [treeNode]
        while (queue.length > 0) {
            let node = queue.shift()
            let newNode = {
                id: node.id,
                name: node.name
            }
            callback && callback(newNode)
            if (node.children) {
                queue.push(...node.children)
            }
        }
    }

    treeList.forEach(rootNode => {
        traverse(rootNode, (node) => {
            list.push(node)
        })
    })

    return list
}



const list = tree2list(data)
console.log('list', list)

@yang49519845
Copy link

yang49519845 commented Feb 1, 2023

function toList(arr) {
  return arr.reduce((prev, current, index) => {
    return prev.concat(current, ...(    current.children && current.children.length > 0 ? toList(current.children) : []   ))
  }, [])
}

@kangkang123269
Copy link

function treeToList(root) {
  const list = [];
  if (!root) {
    return list;
  }
  list.push({ name: root.name });
  for (const child of root.children) {
    list.push(...treeToList(child));
  }
  return list;
}

@Bbbtt04
Copy link

Bbbtt04 commented Mar 12, 2023

const data = [
  {
    id: '1',
    name: '父节点1',
    children: [
      {
        id: '1-1',
        name: '子节点1-1',
        children: [
          {
            id: '1-1-1',
            name: '子节点1-1-1'
          },
          {
            id: '1-1-2',
            name: '子节点1-1-2'
          }
        ]
      }
    ]
  },
  {
    id: '2',
    name: '父节点2',
    children: [
      {
        id: '2-1',
        name: '子节点2-1'
      }
    ]
  }
]


function treeToList(data) {
  let result = []
  data.forEach(item => {
    result.push(item)
    if (item.children) {
      result = result.concat(treeToList(item.children))
      delete item.children
    }
  })
  return result
}
console.log(treeToList(data));


// 无副作用
function treeToList_2(data) {
  let result = []
  data.forEach(item => {
    let obj = {
      id: item.id,
      name: item.name
    }
    result.push(obj)
    if (item.children) {
      result = result.concat(treeToList_2(item.children))
    }
  })
  return result
}
console.log(treeToList_2(data));

@lesenelir
Copy link

function tree2list(data) {
  let res = [],
      path = {}

  traversal(data)
  return res

  function traversal(node) {
    if (!node) return

    path.id = node.id
    path.text = node.text
    path.parentId = node.parentId
    res.push({...path})
    node.children && node.children.forEach(item => {
      traversal(item)
    })
    delete path.id
    delete node.text
    delete node.parentId
  }
}

@dstyxy
Copy link

dstyxy commented Mar 28, 2023

我这个可以不

function treeToList(data) {
  return data.reduce((acc,cur) => {
    if(cur.children) {
      let children = cur.children
      delete cur.children
      acc.push(cur)
      acc.push(...treeToList(children))
      return acc
    } else {
      acc.push(cur)
      return acc
    }
  },[])
}

@woshiarui
Copy link

// 我更喜欢这种,因为在真是业务场景中,应该保留原始解构 // 只是把深层的children拿出来放到第一层 个人想法 function treeToList(data) { if (!Array.isArray(data) && data.length === 0) return; // 方式1 return data.reduce((prev, cur) => { const {children} = cur; return Array.isArray(children) && children.length > 0 ? prev.concat(treeToList(children), cur) : prev.concat(cur); }, []) //方式2 return data.reduce((prev, cur) => { const {children} = cur; return [ ...prev, {...cur}, ...(Array.isArray(children) && children.length > 0 ? treeToList(children) : []) ] }, []) }

第一行代码判断数组和数组长度的应该是或而不是与?

@cscty
Copy link

cscty commented Jun 12, 2023

function treeToList(data) {
let res = [];
function dfs(data) {
for (let i = 0; i < data.length; i++) {
res.push({
id: data[i].id,
text: data[i].text,
parentId: data[i].parentId,
});
if (data[i].children) dfs(data[i].children);
}
}
dfs(data);
return res;
}

@4noth1ng
Copy link

        const data = [
        {
            id: '1',
            name: '父节点1',
            children: [
            {
                id: '1-1',
                name: '子节点1-1',
                children: [
                    {
                        id: '1-1-1',
                        name: '子节点1-1-1'
                    },
                    {
                        id: '1-1-2',
                        name: '子节点1-1-2'
                    }
                ]
            }
            ]
        },
        {
            id: '2',
            name: '父节点2',
            children: [
            {
                id: '2-1',
                name: '子节点2-1'
            }
            ]
        }
        ]
            const formatt = (data) => {
                const res = []
                const formatTree = (cur, parentId = 0) => {
                    const obj = {
                        id: cur.id,
                        name: cur.name,
                        pid: parentId
                    }
                    res.push(obj)
                    if(cur.children && cur.children.length) {      
                        for(const c of cur.children) {
                            formatTree(c, cur.id)
                        }
                    }
                    return obj
                }
                for(const d of data) {
                    formatTree(d)
                }
                return res
            }
            
            console.log(formatt(data));

@Simonduya
Copy link

      function flattenTree(tree, result = []) {
        for (const node of tree) {
          const { children, ...rest } = node;
          console.log(rest);
          result.push(rest);
          if (children && children.length > 0) {
            flattenTree(children, result);
          }
        }
        return result;
      }

      const data = [
        {
          id: 1,
          text: "节点1",
          parentId: 0,
          children: [
            {
              id: 2,
              text: "节点1_1",
              parentId: 1,
            },
          ],
        },
      ];

      const flatData = flattenTree(data);
      console.log(flatData);

@why-ztc
Copy link

why-ztc commented Aug 11, 2023

const tree2list = tree => {
  const res = []
  const dfs = data => {
    for (const item of data) {
      const children = item.children
      Reflect.deleteProperty(item, 'children')
      res.push(item)
      if (Array.isArray(children) && children.length) {
        dfs(children)
      }
    }
  }
  dfs(tree)
  return res
}

@sv-98-maxin
Copy link

function treeToList(treeData, result = []) {
  treeData.forEach(item => {
    if (item.children) {
      treeToList(item.children, result)
      delete item.children
    }
    result.push(item)
  })
  return result
}

@KevinKVJ
Copy link

const treeToListReduce = (data) =>
    data.reduce((reducedArr, { children, ...otherItems }) => {
            const retArr = [...reducedArr, otherItems]
            return Array.isArray(children)
                ? retArr.concat(treeToListReduce(children))
                : retArr;
        }, [])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests