有一个脚本使用搜索从复杂的 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>
当您进行调用时
return
,您将退出循环和函数。因此,不会查看其余元素。要解决,而不是return
仅仅将找到的元素放在某处替代方案:使用发电机