如何使用Jquery从Json中的嵌套数组或嵌套对象中复制数组

时间:2019-03-25 08:01:49

标签: jquery json object multidimensional-array

我得到JSON格式的结果,其中对象可以在对象或数组内。单击函数时,取值并找到该值的对象并附加值

var result={  
"diagnosis":{  
  "Diagnosis":{  
     "head":"Diagnosis",
     "head_id":"18",
     "param":{  
        "10436":"Abortion",
        "10452":"Abscess",
     }
  },
  "ADR-ART":{  
     "head":"ADR-ART",
     "head_id":"19",
     "param":{  
        "120":"A K I",
        "66":"Abdominal Pain

     }
  },
  "ADR-Rx":{  
     "head":"ADR-Rx",
     "head_id":"20",
     "param":{  
        "66":"Abdominal Pain",
        "67":"Alopecia",
        "34":"Anaemia",
        "53":"Anorexia",
     }
  },

 },
 "examination":{  
  "General":{  
     "head":"General",
     "head_id":"8",
     "param":{
        "33":"Anemia",
        "27":"Apthous Ulcers",
        "35":"Ascitis",
     }
  },
  "Skin":{  
     "head":"Skin",
     "head_id":"9",
     "param":{  
        "14":"Alopecia \/ Hair Loss",
        "20":"Angular Cheilitis",
     }
  },
  "Oral":{  
     "head":"Oral",
     "head_id":"10",

我具有诊断,检查等的选择下拉列表。假设我选择检查,则应提取检查对象,并附加所有head和head_id。这就是我尝试过的:

function change_category(objEleme){
var tab_value = $('#head_section_'+objEleme).val(); // value from 1st dropdown list eg : examination
$.each(result.tab_value, function(idx, data){
    console.log(data.head + ' ' + data.head_id);
});return false;

预期输出:

   <option value="8">General</option>
   <option value="9">Skin</option>
   <option value="10">Oral</option>

1 个答案:

答案 0 :(得分:0)

使用result[tab_value]  对于仅用于“常规”的参数,您只需使用嵌套循环

$.each(result[tab_value], function(idx, data){
    console.log(data.head + ' ' + data.head_id);
    if(data.head == "General")
      { $.each(data.param, function(param_idx, param_data)  
         {
             // do something
         });
       }
 });