有一个脚本使用搜索从复杂的 Json 树中选择数据。但只有一个搜索选项进入最终的new_arr数组。例如,在 JSON 字符串中,我有两个具有不同链接的测试元素 - /page和/hello,但生成的数组new_arr只有一个通过链接/page找到的元素。如何确保所有找到的元素最终都在new_arr中?
var treeData='[{"text":"Review","href":"\/","icon":"","target":"_self","page":""},{"text":"Methods","href":"","icon":"","target":"_self","page":"","children":[{"text":"test","href":"/page","icon":"","target":"_self","page":""}]},{"text":"test","href":"/hello","icon":"","target":"_self","page":""}]';
let TREE_DATA = $.parseJSON(treeData);
const findObj = (arr, idToFind) => {
for (const item of arr) {
if (item.text.search(new RegExp(idToFind)) != -1) return item;
if (item.children) {
const recursiveResult = findObj(item.children, idToFind);
if (recursiveResult) return recursiveResult;
}
}
};
$(document).on('input', '#search_methods', function(e) {
var text = $(this).val();
var new_arr = [];
var cString = findObj(TREE_DATA, text);
new_arr.push(cString);
console.log(new_arr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form class="nosubmit">
<input class="nosubmit form-control mb-3" id="search_methods" type="text" placeholder="Search...">
</form>