gpt4 book ai didi

javascript - 使用输入搜索 json

转载 作者:搜寻专家 更新时间:2023-10-31 23:16:19 24 4
gpt4 key购买 nike

我希望设置一个简单的搜索输入来检查 json 文件。

我现在的代码是这样的,这个不行,因为每个json父类都有一个名字。如果我删除名称“json1”/“json2”,它会起作用。

var dataArr = [{
"json1": {
"car": "honda",
"id": "0123",
"name": "jim"
},
"json2": {
"car": "toyota",
"id": "0124",
"name": "james"
}
}];


$("#search").on('keypress keyup change input', function() {
var arrival = $(this).val().toLowerCase();
$('#matches').text(!arrival.length ? '' :
dataArr.filter(function(place) {

return (place.name.toLowerCase().indexOf(arrival) !== -1);
}).map(function(place) {

return place.name;
}).join('\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>this does not work. because i have parent names for my json structure</b>
<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>

这里是代码工作的示例,如果我删除父 json 的“名称”

var dataArr = [{
"car": "honda",
"id": "0123",
"name": "jim"
},
{
"car": "toyota",
"id": "0124",
"name": "james"
}];


$("#search").on('keypress keyup change input', function() {
var arrival = $(this).val().toLowerCase();
$('#matches').text(!arrival.length ? '' :
dataArr.filter(function(place) {
return (place.name.toLowerCase().indexOf(arrival) !== -1);
}).map(function(place) {
return place.name;
}).join('\n'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>this should work</b>
<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>

我该怎么做才能使我的顶级 json 示例正常工作?因为我有一个巨大的 json,其中多个 ID 设置为父名称。

最佳答案

只需像第二个片段数组那样转换第一个片段数组。使用 Object.values()

var dataArr = [{ "json1": { "car": "honda", "id": "0123", "name": "jim" }, "json2": { "car": "toyota", "id": "0124", "name": "james" } }];

dataArr = Object.values(dataArr[0]);
$("#search").on('keypress keyup change input', function() {
var arrival = $(this).val().toLowerCase();
$('#matches').text(!arrival.length ? '' :
dataArr.filter(function(place) {
return (place.name.toLowerCase().indexOf(arrival) !== -1);
}).map(function(place) {
return place.name;
}).join('\n'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>this does not work. because i have parent names for my json structure</b>
<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>

关于javascript - 使用输入搜索 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095889/

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