How to search both parent and child object in Javascript/Lodash/ES6?

痴心易碎 提交于 2019-12-20 07:47:46

问题


So I'm using Vue to filter a list. This consists of the following structure (Baum Hierarchy if anyone is interested):

 [
  {
    "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...",
    }

Each item can have an indefinite amount of children, as can those children, so on and so forth. In my case, I'm only 2 levels deep, so 1 parent can have many (or no) children, but those children can't have children.

I want to search/filter both the parent name field, and name field in the child. If found in the child, I want to return the parent object.

I can filter the parent using Lodash:

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

How do I go about searching both the parent, and the child?


回答1:


you can do it with recursive function

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;


来源:https://stackoverflow.com/questions/41174238/how-to-search-both-parent-and-child-object-in-javascript-lodash-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!