元数据
~~~
const tableData = [
{
province: '江苏',
children: [
{
city: '苏州分拨',
children: [
{
county: 'see',
addr: 'test',
user: '12'
},
{
county: 'see',
addr: 'test',
user: '12'
},
{
county: 'see',
addr: 'test',
user: '12'
}
]
},
{
city: '南通分拨',
children: [
{
addr: 'test',
user: '12'
},
{
county: 'see',
addr: 'test',
user: '12'
}
]
}
]
}
]
~~~
数据处理算法
~~~
export const handleRowCol = (arr, childK = 'children') => {
const newArr = []
const ignore = [childK, '_cache_count', '_cache_keys']
const _extends = (child, parent, ignore) => {
const hasOwn = Object.prototype.hasOwnProperty
Object.keys(parent).forEach(k => {
if (!ignore.includes(k) && !hasOwn.call(child, k)) {
child[k] = parent[k]
}
})
}
const loop = (arr) => {
arr.forEach(ele => {
if (ele[childK] && ele[childK].length) {
ele._cache_keys = Object.keys(ele).filter(key => key !== childK)
loop(ele[childK])
ele._cache_count = ele[childK].reduce((pre, cur) => {
return pre + (cur._cache_count || 1)
}, 0)
}
})
}
const loop2 = (arr, p) => {
arr.forEach((ele, i) => {
if (ele._cache_keys) {
ele._cache_keys.forEach(k => {
ele[k + '_rowspan'] = ele._cache_count
})
}
if (p !== undefined) {
if (i === 0) {
_extends(ele, p, ignore)
} else {
p._cache_keys.forEach(k => {
const key = k + '_rowspan'
if (!(key in ele)) {
ele[key] = 0
}
})
}
if (ele._cache_keys) {
ele._cache_keys = ele._cache_keys.concat(p._cache_keys)
}
}
if (ele[childK] && ele[childK].length) {
loop2(ele[childK], ele)
} else {
newArr.push(ele)
}
})
}
loop(arr)
loop2(arr)
return newArr
}
~~~
处理后数据格式
~~~
[
{
"county": "see",
"addr": "test",
"user": "12",
"city": "苏州分拨",
"city_rowspan": 3,
"province": "江苏",
"province_rowspan": 5
},
{
"county": "see",
"addr": "test",
"user": "12",
"city_rowspan": 0,
"province_rowspan": 0
},
{
"county": "see",
"addr": "test",
"user": "12",
"city_rowspan": 0,
"province_rowspan": 0
},
{
"addr": "test",
"user": "12",
"city": "南通分拨",
"city_rowspan": 2,
"province_rowspan": 0
},
{
"county": "see",
"addr": "test",
"user": "12",
"city_rowspan": 0,
"province_rowspan": 0
}
]
~~~