需要循环的数据
image.png
js将数组转换成树形结构
实验代码:
toTree(data) {
let result = []
if (!Array.isArray(data)) {
return result
}
data.forEach(item => {
delete item.children;
});
let map = {};
data.forEach(item => {
map[item.itemId] = item;
});
for (item in map) {
// let parent = map[item.pid];
// if (map[item.pid] && item.id !== item.pid) {
// if (!item.children) {
// item.children = []
// }
// if (!item.pid._level) {
// item.pid._level = 1
// }
// item._level = temp[item.pid]._level + 1
// item.pid.children.push(item)
// } else {
// res.push(item)
// }
console.log(item);
// if (parent) {
// (parent.children || (parent.children = [])).push(item);
// } else {
// result.push(item);
// }
}
return result;
},
已验证代码:
/**
* 树形数据转换
* @param {*} data
* @param {*} id
* @param {*} pid
*/
export function treeDataTranslate(data, id = 'itemId', pid = 'parentId') {
var res = []
var temp = {}
for (var i = 0; i < data.length; i++) {
temp[data[i][id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
if (temp[data[k].pid] && data[k][id] !== data[k].pid) {
if (!temp[data[k].pid]['children']) {
temp[data[k].pid]['children'] = []
}
if (!temp[data[k].pid]['_level']) {
temp[data[k].pid]['_level'] = 1
}
data[k]['_level'] = temp[data[k].pid]._level + 1
temp[data[k].pid]['children'].push(data[k])
} else {
res.push(data[k])
}
}
return res
}
/**
* 按指定字段分类,树形数据转换
* @param {*} data
* @param {*} id
* @param {*} pid
*/
export function treeDataTranslateByType(oldData, id = 'funID', pid = 'pid', key = 'funID', Type = 'projectId', hasChildren = true) {
var res = []
var temp = {}
var data = []
oldData.map(function(item) {
data.push(item)
})
for (var i = 0; i < data.length; i++) {
var type = data[i][Type] ? data[i][Type] : ''
temp[type + '' + data[i][key] + '' + data[i][id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
var tempKey = ''
oldData.map(function(item) {
if (item[id] === data[k][pid] && item[Type] === data[k][Type] && item[key] < data[k][key]) {
var type = item[Type] ? item[Type] : ''
tempKey = type + '' + item[key] + '' + item[id]
}
})
if (temp[tempKey] && data[k][id] !== data[k][pid]) {
if (!temp[tempKey]['children']) {
temp[tempKey]['children'] = []
}
if (!temp[tempKey]['_level']) {
temp[tempKey]['_level'] = 1
}
if (hasChildren) {
data[k]['_level'] = temp[tempKey]._level + 1
temp[tempKey]['children'].push(data[k])
} else {
data[k]['children']
}
} else {
res.push(data[k])
}
}
return res
}
网友评论