问题
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