首页 > 解决方案 > 如何使用 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"
      }
    ]
  },

任何指导将不胜感激!

标签: javascriptjqueryjson

解决方案


您可以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!");
        }
    });
});

推荐阅读