2011-10-29 152 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; 
} 
相关问题