已知数据格式,实现一个函数 fn 找出链条中所有的父级 id
// 数据
data = [ { "ID": 1, "CreatedAt": "2021-02-25T10:40:25+08:00", "UpdatedAt": "2021-02-25T10:40:25+08:00", "name": "电子产品", "icon": "uploads/productCategory/bgi.png", "parentId": 0, "sort": 0, "level": 0, "status": 1, "children": [ { "ID": 2, "CreatedAt": "2021-02-25T10:40:48+08:00", "UpdatedAt": "2021-02-25T10:40:48+08:00", "name": "手机", "icon": "uploads/productCategory/logo.png", "parentId": 1, "sort": 0, "level": 1, "status": 1, "children": [ { "ID": 3, "CreatedAt": "2021-02-25T10:41:12+08:00", "UpdatedAt": "2021-02-25T10:45:03+08:00", "name": "苹果", "icon": "uploads/productCategory/ios.png", "parentId": 2, "sort": 0, "level": 2, "status": 1, "children": [] }, { "ID": 4, "CreatedAt": "2021-02-25T10:41:39+08:00", "UpdatedAt": "2021-02-25T11:12:05+08:00", "name": "安卓", "icon": "uploads/productCategory/android.png", "parentId": 2, "sort": 0, "level": 2, "status": 1, "children": [] }, { "ID": 6, "CreatedAt": "2021-02-25T10:44:52+08:00", "UpdatedAt": "2021-02-25T10:44:52+08:00", "name": "华为", "icon": "uploads/productCategory/android.png", "parentId": 2, "sort": 0, "level": 2, "status": 1, "children": [] }, { "ID": 7, "CreatedAt": "2021-02-25T10:46:22+08:00", "UpdatedAt": "2021-02-25T10:46:22+08:00", "name": "oppo", "icon": "uploads/productCategory/android.png", "parentId": 2, "sort": 0, "level": 2, "status": 0, "children": [] }, { "ID": 9, "CreatedAt": "2021-02-25T10:48:18+08:00", "UpdatedAt": "2021-02-25T10:48:18+08:00", "name": "小米", "icon": "uploads/productCategory/success.png", "parentId": 2, "sort": 0, "level": 2, "status": 1, "children": [] } ] } ] } ]
方法1
function fn(arr, id) {
// 返回一个数组
var arrRes = [];
if (arr.length == 0) {
return arrRes;
}
var treeHandle = function(data, nodeId) {
for (var i = 0, length = data.length; i < length; i++) {
var node = data[i];
if (node.ID == nodeId) {
if(node.parentId) {
arrRes.unshift(node.parentId)
treeHandle(arr, node.parentId);
}
break;
} else {
if (!!node.children) {
treeHandle(node.children, nodeId);
}
}
}
return arrRes;
}
arrRes = treeHandle(arr, id);
return arrRes;
}
方法2
const fn = (data, value) => {
const dfs = (arr, temp = []) => {
for (const node of arr) {
if (node.ID=== value) {
return temp;
} else if (node.children) {
const result = dfs(node.children, temp.concat(node.ID))
if (result.length > 0) {
return result;
}
}
}
return [];
}
return dfs(data);
}