Алгоритм фильтрации вида дерева по названию и описанию предмета и отображения родителей

1

У меня есть следующие данные древовидной структуры:

  [  
    {  
      "id":132,
      "parent_id":0,
      "title":"Item 1",
      "description":"",
      "nodes":[  
        {  
          "id":133,
          "parent_id":132,
          "title":"Item 1.1",
          "description":"",
          "nodes":[  
            {  
              "id":134,
              "parent_id":133,
              "title":"Item 1.1.1",
              "description":"",
              "nodes":[],        
            }
          ]
        }
      ]
    },
    {
      "id":135,
      "parent_id":0,
      "title":"Item 2",
      "description":"",
      "nodes":[  ]
    },
    { 
      "id":136,
      "parent_id":0,
      "title":"Item 3",
      "description":"",
      "nodes":[ 
        { 
          "id":137,
          "parent_id":136,
          "title":"Item 3.1",
          "description":"",
          "nodes":[ ]    
        }
      ]
    }
  ]

Мне нужно фильтровать по типу и описанию во всех значениях для детей, а если найти дочернее значение, показать всех отцов, следовать иерархии.

Я пытался использовать некоторые подобные, но это только для названия первого родителя:

   this.visible = function (item) {
    return !(this.query && this.query.length > 0 &&
      item.title.indexOf(this.query) == -1);
   };
  • 0
    Вы неправильно this
Теги:
algorithm
treeview

1 ответ

1
Лучший ответ

Как насчет чего-то подобного?

var items =   [  
  {  
    "id":132,
    "parent_id":0,
    "title":"Item 1",
    "description":"",
    "nodes":[  
      {  
        "id":133,
        "parent_id":132,
        "title":"Item 1.1",
        "description":"",
        "nodes":[  
          {  
            "id":134,
            "parent_id":133,
            "title":"Item 1.1.1",
            "description":"",
            "nodes":[],        
          }
        ]
      }
    ]
  },
  {
    "id":135,
    "parent_id":0,
    "title":"Item 2",
    "description":"",
    "nodes":[  ]
  },
  { 
    "id":136,
    "parent_id":0,
    "title":"Item 3",
    "description":"",
    "nodes":[ 
      { 
        "id":137,
        "parent_id":136,
        "title":"Item 3.1",
        "description":"",
        "nodes":[ ]    
      }
    ]
  }
];


function filter(queryFunc, items){
  if (!Array.isArray(items)){
    console.error('Items is not an array!');
    return;
  }
    
  if (typeof queryFunc != 'function'){
    console.error('Please provide a query function.');
    return; 
  }
  
  function descend(item, parents){
    let results = [];
    
    if (queryFunc(item))
      results.push([item, parents])
    
    for (let i=0; i<item.nodes.length; i++)
      results = results.concat(
        descend(item.nodes[i], parents.concat([item.id]))
      );
      
    return results;
  }
  
  let results = [];
  
  for (let i=0; i<items.length; i++)
    results = results.concat(descend(items[i], []));
    
  return results;
}


var as = filter(x => /item\s*1/i.test(x.title), items);
var bs = filter(x => x.title == 'Item 3.1', items);

console.log('as:');
as.map(x => console.log(JSON.stringify(x[0]) + '\n\n Parents: '  + JSON.stringify(x[1])));

console.log('bs:');
console.log(JSON.stringify(bs[0][0]) + '\n\nParents: ' + JSON.stringify(bs[0][1]));
/* https://stackoverflow.com/users/1447675/nina-scholz */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Ещё вопросы

Сообщество Overcoder
Наверх
Меню