我有一系列像这样的房子,
{ "homes" : [{ "home_id" : "1", "address" : "321 Main St", "city" : "Dallas", "state" : "TX", "zip" : "75201", "price" : "925", "sqft" : "1100", "year_built" : "2008", "account_type_id" : "2", "num_of_beds" : "2", "num_of_baths" : "2.0", "geolat" : "32.779625", "geolng" : "-96.786064", "photo_id" : "14", "photo_url_dir" : "\/home_photos\/thumbnail\/2009\/06\/10\/" }], .......... }
我想提供3种不同的搜索方法.
如何返回此家庭区域数组的子集:
在price
X和Y之间
所述bathrooms
> = Z
#bedrooms
= = A或== B或== C.
例如,我如何创建psuedo代码,如:
homes.filter {price >= 150000, price <= 400000, bathrooms >= 2.5, bedrooms == 1 | bedrooms == 3}
user187291.. 15
Javascript 1.6(FF,基于Webkit)具有内置的Array.filter功能,因此无需重新发明轮子.
result = homes. filter(function(p) { return p.price >= 150000 }). filter(function(p) { return p.price <= 400000 }). filter(function(p) { return p.bathrooms >= 2.5 }) etc
对于msie后备,请参阅上面链接的页面.
Javascript 1.6(FF,基于Webkit)具有内置的Array.filter功能,因此无需重新发明轮子.
result = homes. filter(function(p) { return p.price >= 150000 }). filter(function(p) { return p.price <= 400000 }). filter(function(p) { return p.bathrooms >= 2.5 }) etc
对于msie后备,请参阅上面链接的页面.
看看JSONPath http://code.google.com/p/jsonpath/
像jsonPath(json,"$ .. homes [?(@.price <400000)]").toJSONString()之类的东西应该可行.
JAQL对于过滤JSON也很有趣. http://www.jaql.org/
干得好:
var filteredArray = filter(myBigObject.homes, { price: function(value) { value = parseFloat(value); return value >= 150000 && value <= 400000; }, num_of_baths: function(value) { value = parseFloat(value); return value >= 2.5; }, num_of_beds: function(value) { value = parseFloat(value); return value === 1 || value === 3; } });
而filter
功能:
function filter( array, filters ) { var ret = [], i = 0, l = array.length, filter; all: for ( ; i < l; ++i ) { for ( filter in filters ) { if ( !filters[filter](array[i][filter]) ) { continue all; } } ret[ret.length] = array[i]; } return ret; }