tree list 互相转换
本人没有亲测过,有问题的话会重新编辑文档,这篇文章里的代码是积分下载换来的,如果涉及侵权联系我。。。。。看到我这边博客的人可以免积分了。。。。。。
import _ from 'lodash'
export function list2JsonTree(data, options) {
var mainKey = options && options.mainKey || 'id'
var parentKey = options && options.parentKey || 'parentId'
var sortKey = options && options.sortKey || 'seq'
var childListKey = options && options.childListKey || 'children'
var deleteParentKey = options && options.deleteParentKey || true
var deleteSortKey = options && options.deleteSortKey || true
var idItemMap = {}
_.each(data, one => {
// 初始化一下children字段
one[childListKey] = []
idItemMap[one[mainKey]] = one
})
var res = []
_.each(data, one => {
if (one[parentKey] && idItemMap[one[parentKey]]) {
idItemMap[one[parentKey]][childListKey].push(one)
if(deleteParentKey) {
delete one[parentKey]
}
} else {
res.push(one)
if(deleteParentKey) {
delete one[parentKey]
}
}
})
// 排序
return sortJsonTree(res, sortKey, deleteSortKey)
}
export function sortJsonTree(data, key, deleteKey) {
let res = _.sortBy(data, key)
if(deleteKey){
_.each(res, function(one){
delete one[key]
})
}
_.each(data, function (one) {
if (one.children) {
one.children = sortJsonTree(one.children, key, deleteKey)
}
})
return res
}
export function jsonTree2list(data, options, parentId) {
var mainKey = options && options.mainKey || 'id'
var parentKey = options && options.parentKey || 'parentId'
var sortKey = options && options.sortKey || 'seq'
var childListKey = options && options.childListKey || 'children'
var deleteChildListKey = options && options.deleteChildListKey || true
let res = []
_.each(data, function (one, index) {
if (parentId) {
one[parentKey] = parentId
}
res.push(one)
one[sortKey] = index + 1
if (one[childListKey]) {
res = res.concat(jsonTree2list(one[childListKey], options, one[mainKey]))
}
if(deleteChildListKey) {
delete one[childListKey]
}
})
return res
}
// let testData = [
// {id: 1, parentId: 0, name: '1', seq: '2'},
// {id: 2, parentId: 0, name: '2', seq: '4'},
// {id: 3, parentId: 0, name: '3', seq: '3'},
// {id: 4, parentId: 0, name: '4', seq: '1'},
// {id: 5, parentId: 1, name: '11', seq: '2'},
// {id: 6, parentId: 1, name: '12', seq: '3'},
// {id: 7, parentId: 1, name: '13', seq: '1'},
// {id: 8, parentId: 2, name: '21', seq: '2'},
// {id: 9, parentId: 2, name: '22', seq: '1'},
// ]
// let a = JSON.stringify(list2JsonTree(testData), 0, 2)
// console.log(a)
// let b = JSON.stringify(jsonTree2list(JSON.parse(a)),0,2)
// console.log(b)-+
还没有评论,来说两句吧...