nodejs将有父子关系的数据转换成树形数据结构
程序员文章站
2022-06-08 16:37:42
...
数据库里面树形菜单的数据,m_n_id是根节点id,m_p_id是父节点id
未进行处理的数据格式:
处理方法:
function translateDataToTree(data) {
let parents = data.filter(value => value.m_p_id === 'undefined' || value.m_p_id === null || value.m_p_id === '')
let children = data.filter(value => value.m_p_id !== 'undefined' && value.m_p_id !== null && value.m_p_id !== '')
let translator = (parents, children) => {
parents.forEach((parent) => {
children.forEach((current, index) => {
if (current.m_p_id === parent.m_n_id) {
let temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
}
}
)
}
)
}
translator(parents, children)
return parents
}
在需要的地方调用:
let result = translateDataToTree(data)
结果: