遍历数组直到满足条件

时间:2019-03-21 13:25:15

标签: javascript

我有任何带有对象列表的面包屑数组,我想根据当前的面包屑找到其父对象并继续直到parent_id为空

array = [....{id: 1, parent_id: null},{id: 2, parent_id: 1},{id: 3, parent_id: 2},{id: 4, parent_id: 3}...];

breadcrumb_all = [];
current_breadcrumb = {id: 4, parent_id: 3};

for (var i = 0; i < array.length; i++)
{ 
  if ( current_breadcrumb.parent_id  == array[i]['id'] )
   {
      breadcrumb_all.push(array[i]);
   }
}

如何继续循环,直到parent_id为null并将所有值存储在面包屑_全部中。

我可以在parent_id为null的同时和期间使用do来结束循环。我很困惑,请帮忙。

2 个答案:

答案 0 :(得分:3)

如果找到了所需的内容,请从i = 0重新开始循环:

if ( current_breadcrumb.parent_id  == array[i]['id'] ) {
  breadcrumb_all.push(array[i]);
  current_breadcrumb = array[i]; // continue search with this

  if(current_breadcrum.parent_id === null)
    break;

  i = 0; // restart loop
}

我该怎么做:

 function* findChain(values, child) {
   if(child.parent_id === null) return;

   for(const value of values) {
     if(value.id === child.parent_id) {
       yield value;
       yield* findChain(values, value);
       return;
    }
  }
}

 const result = [...findChain(your, data)];

答案 1 :(得分:2)

我相信这应该可以为您提供所需的信息,尽管我不能完全从问题中得出答案。

您可以使用递归函数导航面包屑数组,直到其null,然后返回您拥有的地图:

const array = [{id: 1, parent_id: null},{id: 2, parent_id: 1},{id: 3, parent_id: 2},{id: 4, parent_id: 3}];

const breadcrumbParentMapper = breadcrumbs => (currentBreadcrumb, currentMap=[]) => {
  const mapWithThisCrumb = [
    ...currentMap,
    currentBreadcrumb,
  ];

  if (currentBreadcrumb.parent_id === null) {
    return mapWithThisCrumb;
  }
  
  const parentCrumb = breadcrumbs.find(crumb => crumb.id === currentBreadcrumb.parent_id);
  
  if (parentCrumb === undefined) {
    return mapWithThisCrumb;
  }
  
  return breadcrumbParentMapper(
    breadcrumbs
  )(
    breadcrumbs.find(crumb => crumb.id === currentBreadcrumb.parent_id),
    mapWithThisCrumb
  )
}

const current_breadcrumb = {id: 4, parent_id: 3};

const mapper = breadcrumbParentMapper(array);

const result = mapper(current_breadcrumb);

console.dir(result)