gpt4 book ai didi

javascript - 如何遍历树并过滤javascript中的匹配节点?

转载 作者:行者123 更新时间:2023-11-30 20:42:23 24 4
gpt4 key购买 nike

我尝试过过滤节点,但只成功过滤了根节点。我的实现如下。我如何使用一种方法来过滤子节点?

  function getMatchedValues(nodes)
{
var leafContainsText = false;

for (var i = 0; i < nodes.length; i++)
{
if (nodes[i].items && nodes[i].items.length > 0)
{
leafContainsText = getMatchedValues(nodes[i].items);
if (leafContainsText)
break;
}
else
{
if (nodes[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
{
leafContainsText = true;
break;
}
}
}

return leafContainsText;
}


$scope.temp_reports = [];

for (var i = 0; i < $scope.reports.length; i++)
{
if ($scope.reports[i].items && $scope.reports[i].items.length > 0)
{
if (getMatchedValues($scope.reports[i].items))
$scope.temp_reports.push($scope.reports[i]);
else if ($scope.reports[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
$scope.temp_reports.push($scope.reports[i]);
}
else
{
if ($scope.reports[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
$scope.temp_reports.push($scope.reports[i]);
}
}

树对象 ($scope.reports) 如下所示:

     [
{
text:"abc",
items:[
{
text:"abf"
},
{
text:"abd",
items:[
{
text:"bbb"
},
{
text:"dba"
}
]
}
]
},
{
text:"def",
items:[
{
text:"ddf"
},
{
text:"ddd",
items:[
{
text:"dfg"
},
{
text:"dba",
items:[
{
text:"qqq"
},
{
text:"www"
}
]
}
]
}
]
}
]

例如,如果要过滤包含'd'的节点,那么结果树应该是这样的;

         [
{
text:"abc",
items:[
{
text:"abd",
items:[
{
text:"dba"
}
]
}
]
},
{
text:"def",
items:[
{
text:"ddf"
},
{
text:"ddd",
items:[
{
text:"dfg"
},
{
text:"dba",
items:[]
}
]
}
]
}
]

最佳答案

您也可以通过过滤 items 数组来过滤数组。

这个解决方案改变了原始数据。

function filter(array, search) {
return array.filter(function f(o) {
var t;

if (o.items) {
t = o.items.filter(f);
}
if (o.text.includes(search) || t && t.length) {
if (t) {
o.items = t;
}
return true;
}
});
}

var array = [{ text: "abc", items: [{ text: "abf" }, { text: "abd", items: [{ text: "bbb" }, { text: "dba" }] }] }, { text: "def", items: [{ text: "ddf" }, { text: "ddd", items: [{ text: "dfg" }, { text: "dba", items: [{ text: "qqq" }, { text: "www" }] }] }] }],
result = filter(array, 'd');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何遍历树并过滤javascript中的匹配节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com