javascript - 如何使用 jQuery 搜索嵌套的 JSON 数组?
问题描述
我正在尝试遍历 JSON 文件中的“机器”对象数组(下面粘贴的示例对象)。每个对象都包含一个嵌套的软件数组,我希望能够通过输入字段动态搜索这些软件。即识别用户输入字符串(例如“Unreal”)与安装了名称包含“Unreal”的软件的机器之间的匹配。
我已经创建了下面的算法来搜索每个 JSON 对象顶层中的其他对象,我认为它会是类似的,但到目前为止,反复试验并没有很好地为我服务!
考虑到该值是对象的更深层次,简单地添加 value.software.product_name 来检索每个软件名称是行不通的。
$.getJSON('../assets/mbid_directory.json', function(data){
$.each(data, function(key, value){
if(value.general.building_name.search(expression) != -1 || value.general.room_name.search(expression) != -1 || value.hardware.cpu.search(expression) != -1 ||
value.hardware.memory.search(expression) != -1 || value.hardware.gpu.search(expression) != -1 || value.hardware.screen_resolution.search(expression) != -1 ||
value.hardware.notable_peripherals.search(expression) != -1) {
//do something
}
})
})
{
"general": {
"machine_id": 2,
"machine_ip_address": "192.168.0.18",
"building_name": "Mellor",
"room_name": "S509",
"map_location": {
"lat": "-25.363",
"lng": "131.044"
}
},
"hardware": {
"cpu": "AMD Ryzen 5 3570K 3.40GHz",
"memory": "8GB DDR3 2600Ghz",
"gpu": "Nvidia GTX 790 Ti 3GB",
"screen_resolution": "1920x1200",
"notable_peripherals": "Dual-monitors"
},
"software": [
{
"product_title": "Windows 10 Education",
"product_version": "6.2.9200.16384"
},
{
"product_title": "Unreal Engine Games Studio",
"product_version": "8.4.2"
},
{
"product_title": "Microsoft Visual Studio 2017",
"product_version": "5.5.106.3"
}
]
},
任何指导将不胜感激!
解决方案
您可以filter
在软件阵列上使用,例如:
$.getJSON('../assets/mbid_directory.json', function(data){
$.each(data, function(key, value){
if (value.general.building_name.search(expression) != -1 ||
value.general.room_name.search(expression) != -1 ||
value.hardware.cpu.search(expression) != -1 ||
value.hardware.memory.search(expression) != -1 ||
value.hardware.gpu.search(expression) != -1 ||
value.hardware.screen_resolution.search(expression) != -1 ||
value.hardware.notable_peripherals.search(expression) != -1 ||
value.software.filter(function(elem){
return elem.product_title.search(expression) != -1 ||
elem.product_version.search(expression) != -1
}).length > 0) {
console.log("Match!");
}
});
});
推荐阅读
- c# - 将参数传递给表达式时解构方法调用表达式
- python - 如何在熊猫中将日期转换为一种格式?
- vue.js - 浏览器控制台出错,请求 /sockjs-node/info?t=1555629946494
- c++ - 通过 boost::asio::buffer() 发送 Object*
- prolog - 试图定义的问题恰好存在于 Prolog 中
- javascript - 节点 - 异步循环不等待导致 Mongo 过早断开连接
- python - 仅使用互联网导入 python 模块
- c# - 有没有可能修复以前工作的表格,现在我将它粘贴到另一个表格中它不会工作?
- javascript - 使用 window.open 打开存储在变量中的 URL
- html - 如果无效输入是禁用祖先的一部分,我如何突出显示它们?