2011-10-29 76 views
1

我需要能夠識別某些JSON響應的某些屬性,這些屬性的格式不總是相同的。例子中的一個片段是:jQuery - 在json中查找某些屬性

{ 
    "Attributes" : [ 
     { 
     "Value" : "4 bedrooms", 
     "DisplayName" : "Bedrooms", 
     "Name" : "bedrooms" 
     }, 
     { 
     "Value" : "2 bathrooms", 
     "DisplayName" : "Bathrooms", 
     "Name" : "bathrooms" 
     }, 
     { 
     "Value" : "House", 
     "DisplayName" : "Property type", 
     "Name" : "property_type" 
     }, 
     { 
     "Value" : "$780,000", 
     "DisplayName" : "Rateable value", 
     "Name" : "rateable_value" 
     }, 
     { 
     "Value" : "Price by negotiation", 
     "DisplayName" : "Price", 
     "Name" : "price" 
     }, 
     { 
     "Value" : "13 Wellswood Way\r\nLower Shotover\r\nQueenstown-Lakes\r\nOtago", 
     "DisplayName" : "Location", 
     "Name" : "location" 
     }, 
     { 
     "Value" : "Queenstown-Lakes", 
     "DisplayName" : "District", 
     "Name" : "district" 
     }, 
     { 
     "Value" : "Lower Shotover", 
     "DisplayName" : "Suburb", 
     "Name" : "suburb" 
     }, 
     { 
     "Value" : "Otago", 
     "DisplayName" : "Region", 
     "Name" : "region" 
     }, 
     { 
     "Value" : "254m²", 
     "DisplayName" : "Floor area", 
     "Name" : "floor_area" 
     }, 
     { 
     "Value" : "1690m²", 
     "DisplayName" : "Land area", 
     "Name" : "land_area" 
     }, 
     { 
     "Value" : "CBM959", 
     "DisplayName" : "Property ID#", 
     "Name" : "property_id" 
     }, 
     { 
     "Value" : "playground,tennis,hiking,biking,historic bridge walk,buses,5 mins to shops.", 
     "DisplayName" : "In the area", 
     "Name" : "in_the_area" 
     }, 
     { 
     "Value" : "Large double garage.Plenty off-street parking.Extra for boat+ etc.", 
     "DisplayName" : "Parking", 
     "Name" : "parking" 
     } 
    ] 
} 

正如你所看到的名稱,顯示名稱和值重複每個屬性。我不知道該怎麼做是通過這些屬性來找到一個特定的屬性。例如,我將如何獲得Bathrooms的價值?

感謝您的幫助 亞當

回答

0
function getAttributesByName(arr,name){ 
    for(var i=0,l=arr.length;i<l;i++) 
     if(arr[i].Name === name) 
      return arr[i]; 
    return null;    
} 

更jQuery的方法:

function getAttributesByName(arr,name){ 
    var result = null; 
    $.each(arr,function(){ 
     if(this.Name === name) 
      result = this; 
    }); 
    return result; 
} 
0

這裏是:

var a = data.Attributes; 
for(var i in a) { 
    if(a.hasOwnProperty(i) && a[i].Name == 'bathrooms') 
     return a[i].Value; 
} 
相關問題