如何在Javascript / Lodash / ES6中搜索父项和子对象? [英] How to search both parent and child object in Javascript/Lodash/ES6?
问题描述
所以我使用Vue过滤列表。这包括以下结构(如果有人有兴趣,请 Baum Hierarchy ):
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...",
}
每个项目都可以有一个无限期的孩子,以及那些孩子,等等。在我的情况下,我只有2级深度,所以1个父母可以有很多(或不)孩子,但是那些孩子不能有孩子。
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.
我可以使用Lodash过滤父母:
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?
推荐答案
可以使用递归函数来执行
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;
这篇关于如何在Javascript / Lodash / ES6中搜索父项和子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!