gpt4 book ai didi

javascript - Jquery 搜索 JSON 数组

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

<script>
var data = [
{
"BP": "Title",
"Attr": ["Attr 1", "Attr2"],
"Tables": ["Fact", "Fact", "Fact", "Fact", "Fact"],
"Vendor": ["Vendor1"],
"BO": ["Vxy", "XYZ"]
},
{
"BP": "KYB",
"Attr": ["Attr 1", "Attr2"],
"Tables": ["Data Not Persisted"],
"Vendor": ["LX"],
"BO": ["JXA", "HJZ"]
}];

$(document).ready(function() {

$.ajaxSetup({
cache: false
});

$('#search').keyup(function() {

$('#result').html('');
$('#state').val('');

var searchField = $('#search').val();

// i makes the search case insensitive
var expression = new RegExp(searchField, "i");

console.log(expression)

$.each(data, function(key, value) {
if (value.BP.search(expression) != -1 || value.Tables.search(expression) != -1) {
$('#result').append('<li class="list-group-item link-class">' + value.Vendor + '|<span class="text-muted">' + value.BP + '|<span class="text-muted">' + value.Tables + '</li>');
//console.log(value.Tables);
}
});
});

$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
</script>

我正在尝试对我的 JSON 对象进行实时 JSON 搜索。它适用于只有 1 个元素的属性,但当某些属性(例如“表格”)具有元素数组时失败。

我得到以下异常。

value.Tables.search is not a function at Object. (test_ds.html:173) at Function.each (jquery.min.js:2) at HTMLInputElement. (test_ds.html:172) at HTMLInputElement.dispatch (jquery.min.js:3) at HTMLInputElement.q.handle (jquery.min.js:3)

最佳答案

遍历字符串数组

Tables 变量应该分段访问,因为访问它作为一个整体将返回一个数组。

我不知道您的 value.Tables.search 代码在哪里,但是,您可以将其替换为如下内容:

value.Tables.some(table => table.search(....))

这是有效的,因为如果 Tables 中的任何字符串通过条件函数,.some 返回 true,在您的情况下这是 .search

关于javascript - Jquery 搜索 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51180490/

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