多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] >[success] # 查找所有父级数据 ~~~ let obj = [ // 树形数据结构 { code: "PERM_10000", name: "基础数据", subList: [ { code: "PERM_10004", parentCode: "PERM_10000", name: "桥梁数据", subList: [ { code: "PERM_10021", parentCode: "PERM_10004", name: "部件管理", subList: [ { code: "PERM_10022", parentCode: "PERM_10021", name: "查看列表" }] } ] }] } ] /** * 根据id或者code查找所有父级数据 * @param {Array} data2 - 数据源 * @param {Array} parentCode2 - 要过滤的parentCode或parentId */ function getParent(data2, parentCode2) { let arrRes = []; if (data2.length == 0) { // 无数据 return arrRes; } let rev = (data, parentCode) => { // 有数据 for (let i = 0, length = data.length; i < length; i++) { let node = data[i]; if (node.code == parentCode) { // 要对比的id或code,parentId或parentCode arrRes.unshift(node) rev(data2, node.parentCode); // 要对比的id或code,parentId或parentCode break; } else { if (!!node.subList) { // child rev(node.subList, parentCode); // 要对比的id或code,parentId或parentCode } } } return arrRes; }; arrRes = rev(data2, parentCode2) return arrRes; } let filterData = getParent(obj, 'PERM_10021') // 根据子级别id找所有父级(祖宗) console.log(JSON.stringify(filterData)) // 返回数据格式 // [ // { code: 'PERM_10000', name: '基础数据', subList: [ [Object] ] }, // { code: 'PERM_10004', parentCode: 'PERM_10000', name: '桥梁数据', subList: [ [Object] ] }, // { code: 'PERM_10021', parentCode: 'PERM_10004', name: '部件管理', subList: [ [Object] ] } // ] ~~~