2016-12-15 9 views
0

私はVueを使ってリストをフィルタリングしています。 (誰もが興味を持っている場合Baum Hierarchy)これは次の構造で構成されていますJavascript/Lodash/ES6で親オブジェクトと子オブジェクトの両方を検索するには?

[ 
    { 
    "id": 61, 
    "created_at": "2016-11-23 22:07:10", 
    "updated_at": "2016-12-15 19:44:56", 
    "parent_id": null, 
    "lft": 107, 
    "rgt": 116, 
    "depth": 0, 
    "name": "Quia eos voluptas molestiae ut cum.", 
    "slug": "consequatur-voluptatum-dolores-non-perferendis-possimus", 
    "order_column": null, 
    "belongs_to": null, 
    "children": [ 
     { 
     "id": 57, 
     "created_at": "2016-11-23 22:07:10", 
     "updated_at": "2016-12-15 19:44:56", 
     "parent_id": 61, 
     "lft": 110, 
     "rgt": 113, 
     "depth": 1, 
     "name": "Molestias vitae velit doloribus.", 
     "slug": "enim-itaque-autem-est-est-nisi", 
     "order_column": null, 
     "belongs_to": null, 
     "children": [] 
    },{ 
     "name": "etc...", 
    } 

子どもたちができるように、各項目はようになど、子どもの不確定量を持つことができます。私の場合、私は2レベルしかないので、1人の親は多くの(または全く)子供を持つことができますが、それらの子供は子供を持つことができません。

は、私が子供に/フィルタの両方の親フィールド、および名前フィールドを検索したいです。子で見つかった場合は、親オブジェクトを返したい。私は親と子の両方を検索する行くにはどうすればよい

  let search = this.search; 
      return _.filter(this.sortable, function(item) { 
       return item.name.search(new RegExp(search, "i")) !== -1; 
      }); 

私はLodashを使用して親をフィルタリングすることができますか?

答えて

1

あなたは再帰関数で

var res = _.reduce(this.sortable, function reducer(result, item) { 
    if (item.name.search(new RegExp(search, "i")) !== -1) { 
     result.items = _.concat(result.items, result.parent || item); 
    } 
    result.items = _.concat(
     result.items, 
     _.reduce(item.children, reducer, {parent: item, items: []}).items 
    ) 
    return result; 
}, {items: []}).items; 
+0

うわー、私はそのことを考えたことがないが、それを行うことができます!それは完璧に動作します!どうもありがとうございます – Kingsley

関連する問題