简体   繁体   English

Javascript递归函数获取给定节点的所有子节点

[英]Javascript recursive function to get all children for given node

I have written a recursive function to get get all children (and children of each child and so on).我写了一个递归函数来获取所有孩子(以及每个孩子的孩子等等)。 But I am not able to return correct value from the function.但是我无法从函数返回正确的值。 I see that function actually make the list of the data which I want but somehow I am not able to return it from the for loop.我看到该函数实际上列出了我想要的数据,但不知何故我无法从 for 循环中返回它。

 let data = [ { "nodeId": "root", "name": "ROOT", "parentNodeId": null }, { "nodeId": "1", "name": "one", "parentNodeId": "root" }, { "nodeId": "2", "name": "Two", "parentNodeId": "1" }, { "nodeId": "31", "name": "three", "parentNodeId": "2" }, { "nodeId": "32", "name": "three-2", "parentNodeId": "2" }, { "nodeId": "33", "name": "three-3", "parentNodeId": "2" }, { "nodeId": "41", "name": "four 2-1", "parentNodeId": "32" }, { "nodeId": "51", "name": "five 2-1-1", "parentNodeId": "41" }, { "nodeId": "61", "name": "six 2-1-1-1", "parentNodeId": "51" }, { "nodeId": "62", "name": "six 2-1-1-2", "parentNodeId": "51" }, { "nodeId": "71", "name": "seven 2-1-1-2-1", "parentNodeId": "62" }, { "nodeId": "81", "name": "eight 2-1-1-2-1-1", "parentNodeId": "71" }, { "nodeId": "91", "name": "nine 2-1-1-2-1-1-1", "parentNodeId": "81" }, { "nodeId": "101", "name": "ten 2-1-1-2-1-1-1-1", "parentNodeId": "91" }, { "nodeId": "111", "name": "eleven 2-1-1-1-1", "parentNodeId": "101" } ] function test(entities, id, result = []) { const childrens = entities.filter(x => x.parentNodeId === id) if (childrens.length === 0) { console.log('inside1', result) return result } result = [...result, ...childrens] for (const ele of childrens) { test(entities, ele.nodeId, result) } } const out = test(data, '32') console.log('out', out)

if I pass '32' in below function, I want to get 32 and all of its children.如果我在下面的函数中传递 '32',我想得到 32 及其所有子项。 So it should exclude root, 1, 2, 31 and 33. everything from 32 and downwards should be returned from the recursive function.所以它应该排除 root、1、2、31 和 33。递归函数应该返回 32 及以下的所有内容。

You need to update the result array within the for loop and return the updated array:您需要在 for 循环中更新结果数组并返回更新后的数组:

function test(entities, id, result = []) {
  const childrens = entities.filter(x => x.parentNodeId === id);

  if (childrens.length === 0) {
    return result;
  }
  result = [...result, ...childrens];
  for (const ele of childrens) {
    result = test(entities, ele.nodeId, result);
  }
  return result;
}

const out = test(data, '32');
console.log('out', out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM