Java教程

javascript中树结构数据转换

本文主要是介绍javascript中树结构数据转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/** 扁平化数据变成树 */
const _iteration = (_target = [], { _id = "id", pid = "pid", children = "children", rootId = "root" } = {}) => {
	let _parentMap = new Map()
	const target = JSON.parse(JSON.stringify(_target))
	let result = [];
	for (const item of target) {
		if (_parentMap.has(item[_id])) {
			item[children] = _parentMap.get(item[_id])[children]
		} else {
			item[children] = []
		}
		_parentMap.set(item[_id], item)
		if (_parentMap.has(item[pid])) {
			_parentMap.get(item[pid])[children].push(item)
		} else {
			_parentMap.set(item[pid], { [children]: [item] })
		}
		if (String(item[pid]) === String(rootId)) {
			result.push(item)
		}
	}
	return { result, _parentMap };
}
/** 扁平化数据变成树 */
const listToTree = (_target = [], { id = "id", parentId = "parentId" } = {}) => {
	let info = _target.reduce((map, node) => (map[node[id]] = node, node.children = [], map), {})
	return _target.filter(node => {
		info[node[parentId]] && info[node[parentId]].children.push(node)
		return !node[parentId]
	})
}
// /** 扁平化数据变成树 */
const dataToTree = (_target = [], { id = "id", parentId = "parentId" } = {}) => {
	return res = _target.filter(r => !r[parentId]).map(r => ({ 
		...r, children: _target.filter(rr => rr[parentId] === r[id]) 
	}))
}
这篇关于javascript中树结构数据转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!