我有一个像数据一样的树形结构,我想在其中执行搜索,然后仅返回包括根父节点在内的特定子节点。搜索基本上基于用户输入的文本在父子节点及其子节点上进行。请检查以下示例代码。另外,我们如何优化代码以获得以下预期结果?
示例:在结果1中,它应类似于Android->硬件-> NFC和Iphone->硬件-> NFC
[{"Id":1,"Name":"Andriod","children":[{"Id":1,"Name":"Hardware","children":[{"Id":3,"Name":"NFC"}]},{"Id":2,"Name":"Iphone","children":[{"Id":1,"Name":"Hardware","children":[{"Id":3,"Name":"NFC"}]}]}]
示例:在结果2中,它应类似于Android->硬件->子节点和Iphone->硬件->子节点
[{"Id":1,"Name":"Andriod","children":[{"Id":1,"Name":"Hardware","children":[{"Id":1,"Name":"Dual Sim"},{"Id":2,"Name":"LTE"},{"Id":3,"Name":"NFC"}]},{"Id":2,"Name":"Iphone","children":[{"Id":1,"Name":"Hardware","children":[{"Id":1,"Name":"Single Sim"},{"Id":2,"Name":"LTE"},{"Id":3,"Name":"NFC"}]}]
//data tree list
var dataList = [{
Id: 1, Name : 'Andriod', children:
[{
Id: 1, Name : 'Hardware', children: [
{Id: 1, Name : 'Dual Sim'},
{Id: 2, Name : 'LTE'},
{Id: 3, Name : 'NFC'}
]
},
{Id: 2, Name : 'Software', children:
[
{Id: 1, Name : 'Nougot'},
{Id: 2, Name : 'Oreo'}
]
}]
},
{Id: 2, Name : 'Iphone', children:
[{
Id: 1, Name : 'Hardware', children: [
{Id: 1, Name : 'Single Sim'},
{Id: 2, Name : 'LTE'},
{Id: 3, Name : 'NFC'}
]},
{Id: 2, Name : 'Software', children:
[
{Id: 1, Name : 'iOS 11'},
{Id: 2, Name : 'iOS 10'}
]
}]
}]
//Search Criteria
var searchText = "NFC";
var searchText2 = "Hardware";
//Search logic
function searchData(val)
{
var isFound = false;
var searchList = $.grep(dataList, function(firstNode)
{
if($.isArray(firstNode.children))
{
$.grep(firstNode.children, function(childNode)
{
if(childNode.Name.toLowerCase().indexOf(val.toLowerCase()) > -1)
{
isFound = true;
return;
//return firstNode;
}
else if($.isArray(childNode.children))
{
$.grep(childNode.children, function(childchildNode)
{
if(childchildNode.Name.toLowerCase().indexOf(val.toLowerCase()) > -1)
{
isFound = true;
return;
//return firstNode;
}
})
}
})
}
if(isFound)
{
isFound = false;
return firstNode;
}
})
return searchList;
}
var a= searchData(searchText);
var b= searchData(searchText2);
$("#result1").html(searchText+" text Results -- " +JSON.stringify(a));
$("#result2").html(searchText2+" text Results -- "+JSON.stringify(b));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Result
<div id="result1">
</div>
<br/>
<br/>
<div id="result2">