How to index hierarchical data?

I have some hierarchical data that can be represented through two data structures.

The first is a layered JSON object, as shown below:

[
    { 
        "text": "Item 1, "children": [
            {"text": "Nested item 1"}, 
            {"text": "Nested item 2"}] 
    },
    {
        "text": "Item 2", "children": []
    }
]

And the second structure is an array. Elements of this array are connected id-parentId.

[
    {id: 1, text: "Item 1", parentId: null},
    {id: 2, text: "Nested item 1", parentId: 1}
]

I need to filter this data using some substring.

To implement this functionality, I want to create a search index. And then feed the filter operation to the created index.

The main reason for creating a search index is to use one filtering algorithm instead of two different approaches to filtering hierarchical data and a list id-parentId.

So the question is, what format should the search index have? I am currently using something like this:

[
    {id: 1, text: "item 1", parentKey: null, childrenKeys: [2,3]},
    {id: 2, text: "child 1", parentKey: 1, childrenKeys: []},
    {id: 3, text: "child 2", parentKey: 1, childrenKeys: []}  
]

: .

: , .

+4
1

, .

Array.prototype.reduce( Array.prototype.filter, / bind).

JSFiddle http://jsfiddle.net/5q4cdevt/

/* @this {string} search value */ 
function reduceContains(result, obj) {
    if(obj.text.indexOf(this) >= 0) { 
        result.push(obj); 
    }
    if(obj.children) {
        obj.children.reduce(reduceContains.bind(this), result);
    }
    return result;
}

console.log([
    { 
        "text": "Item 1", "children": [
            {"text": "Nested item 1"}, 
            {"text": "Nested item 2"}] 
    },
    {
        "text": "Item 2", "children": []
    }
].reduce(reduceContains.bind("Nested"), []));

console.log([
    {id: 1, text: "Item 1", parentId: null},
    {id: 2, text: "Nested item 1", parentId: 1}
].reduce(reduceContains.bind("Nested"), []));
+2

Source: https://habr.com/ru/post/1609442/


All Articles