[英]jquery each iterating over complex JSON structure with “where clause”
我不是100%清楚如何制定$.each()
函數。
以下JSON數據塊在數組ItemValues
包含多個項目。 我正在尋找的是一種方法(因為此數據包可以任意大)在某種程度上是為了獲取每個ItemValue
數組項WHERE Fields.Id
等於某個值“ x”。
同樣,是否有一些方法可以將ItemValues[n].Fields.units
檢索為數組?
{
"CacheName":"Default",
"LastUpdateTime":"\/Date(1396994130568)\/",
"Type":"Start",
"TotalItemsCount":3,
"PassingFilterCount":3,
"ItemValues":[
{
"Fields":{
"id":"13288263",
"status":"8",
"x_cord":"7250600",
"y_cord":"566620200",
"code":"1021",
"sub_code":"1W",
"priority":"1",
"units":"1011, 1130, 1201, 1233, 1445, 1501, 1518, 1714, 1726, 1823, 1825, 1832, 3662",
"ts":"20140402234025UT"
},
"Id":"13288263",
"LastAction":"add"
},
{
"Fields":{
"id":"13288264",
"status":"8",
"x_cord":"",
"y_cord":"",
"code":"",
"sub_code":"",
"priority":"-1",
"units":"",
"ts":""
},
"Id":"13288264",
"LastAction":"add"
},
{
"Fields":{
"id":"13288265",
"status":"8",
"x_cord":"",
"y_cord":"",
"code":"",
"sub_code":"",
"priority":"-1",
"units":"",
"ts":""
},
"Id":"13288265",
"LastAction":"add"
}
]
}
假設您顯示的json在變量json
,那么對於這種確切的情況,您可以使用:
function validItems(id,json){
var validItemValues = [];
var values = json.ItemValues;
for(var value in values){
if( !values.hasOwnProperty(value) )continue;
var itemValue = values[value];
if( itemValue.Fields.id == id ){
validItemValues.push(itemValue);
}
}
return validItemValues;
}
使用jQuery的.each
相同方法:
function validItems(id,json){
var validItemValues = [];
$.each(json.ItemValues,function(){
if(this.Fields.id == id)validItemValues.push(this);
});
return validItemValues;
}
有關查找json值的遞歸方法,請參見以下答案: https : //stackoverflow.com/a/11657379/1026459
一旦有了有效項,就可以遍歷它們,然后使用split將unites字符串轉換為數組。
var validItemList = validItems(id,json);
for( var item in validItemList ){
if( !validItemList .hasOwnProperty(item ) )continue;
var currentItem = validItemList[item];
var fieldsUnitArray = currentItem.Fields.units.split(" ");
//work with array of units
}
這是一個顯示所有內容的代碼(根據需要使用$.each()
), JSON.parse()和String.split()
var json_string = "Your JSON here";
//Use JSON.parse to make it an object
var json_object = JSON.parse(json_string.innerHTML);
//Will store the matched identifier
var matched_id;
//Will store the matched array
var matched_array;
//A valid test case, with units not null
var x = 13288263;
$.each(json_object.ItemValues, function(key, item_value){
if(item_value.Fields.id == x){
matched_id = item_value.Fields.id;
//Second part of the question
var units = item_value.Fields.units;
if(units != ""){
//String.split() returns an array, by splitting the string with
//selected string
matched_array = units.split(', ');
}
}
});
這是一個演示 ,可以使用它。
注意:肯定有一些更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.