美文网首页
算法查询树并拼接名称

算法查询树并拼接名称

作者: 暖暖1500 | 来源:发表于2022-02-18 14:38 被阅读0次
function getParentLabelByValue(
  array: Array<any>,
  id: string|number,
  fieldNames: FilesName = { value: 'id', label: 'name', children: 'children' }
): Array<string> {
  const stack = [];
  let going = true;
  const walker = (array, id) => {
    array.forEach((item: any) => {
      if (!going) return;
      stack.push(item[fieldNames.label]);
      if (item[fieldNames.value] === id) {
        going = false;
      } else if (item[fieldNames.children]) {
        walker(item[fieldNames.children], id);
      } else {
        stack.pop();
      }
    });
    if (going) stack.pop();
  };
  walker(array, id);
  return stack;
}

相关文章

网友评论

      本文标题:算法查询树并拼接名称

      本文链接:https://www.haomeiwen.com/subject/oulylrtx.html