lz在用element-ui时候 用到Cascader 级联选择器多选的时候 是要进行通过子节点查找所有的父节点的需求;于是有了下面的代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>find family</title> <script type="text/javascript"> var json = [{ id: 1, parentId: null, children: [{ id: 10, parentId: 1, children: [{ id: 101, parentId: 10 }] }, { id: 11, parentId: 1, children: [{ id: 110, parentId: 11 }] }] }] </script> <script type="text/javascript"> var parentNode = null; var node = null; function getNode(json, target) { for (var i = 0; i < json.length; i++) { if (node) { break; } var obj = json[i]; if (!obj || !obj.id) { continue; } if (obj.id == target) { node = obj; if (obj.parentId) { parentNode = { id: obj.parentId }; } break; } else { if (obj.children && obj.children.length != 0) { getNode(obj.children, target) } else { continue; } } } if (!node) { parentNode = null; } return { parentNode: parentNode, node: node }; } var query = 101; var result = []; var getResult = function (json, query) { node = null; parentNode = null; var obj = getNode(json, query); if (obj.parentNode) { getResult(json, obj.parentNode.id); result.push(obj.parentNode.id); } return result; } getResult(json, query); console.log(result); </script> </head> <body> </body> </html>
改某个网友的代码;之前的这位网友写的是有bug的;
原文地址:https://www.cnblogs.com/zdf-xue/p/11503600.html
时间: 2024-10-11 11:55:10