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])
}))
}
标签:node,转换,target,树结构,javascript,id,item,parentId,children 来源: https://blog.csdn.net/m0_54944506/article/details/122104976