算法查询树并拼接名称

2022-02-18  本文已影响0人  暖暖1500
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;
}
上一篇 下一篇

猜你喜欢

热点阅读