将有id和父级id的正常json数组改变为有children内嵌字段的方法(俄罗斯套娃,可用于树形控件和树形表格的生成,纯js原生代码,不需要其它依赖)
treeDataFormat(data, idField, parIdField, textField, openClose, rootId) { idField = idField || "id";//目标依据id parIdField = parIdField || "parent_id";//父级id textField = textField || "name";//文本字段 rootId = rootId || 0; if (data && data.length > 0) { var dataMapping = {}; for (var i = 0; i < data.length; i++) { // dataMapping[data[i][idField]] = $.extend({}, data[i]); dataMapping[data[i][idField]] = data[i]; // dataMapping[data[i][idField]].children = []; dataMapping[data[i][idField]].text = dataMapping[data[i][idField]][textField]; dataMapping[data[i][idField]].state = openClose || "open"; } //构造上下级关系 for (var i = 0; i < data.length; i++) { var tempData = data[i]; if (tempData[parIdField] && dataMapping[tempData[parIdField]]) { dataMapping[tempData[parIdField]].children = dataMapping[tempData[parIdField]].children || []; dataMapping[tempData[parIdField]].children.push(dataMapping[tempData[idField]]); } } var treeArray = []; for (var key in dataMapping) { if (dataMapping[key].child_count != null || dataMapping[key].child_count != undefined) { //查询出已明确定义子节点的数目 if (dataMapping[key].child_count > 0) { //有子节点 if (!dataMapping[key].children || dataMapping[key].children.length == 0) { dataMapping[key].state = "closed"; } else { dataMapping[key].state = "open"; } } else { //无子节点 dataMapping[key].state = "open"; } } else { if (!dataMapping[key].children || dataMapping[key].children.length == 0) { dataMapping[key].state = "open"; } } if (dataMapping[rootId]) {} else { if (dataMapping[key][parIdField] == rootId) { treeArray.push(dataMapping[key]); } } } if (dataMapping[rootId]) { treeArray.push(dataMapping[rootId]); } return treeArray; } return []; };