JavaScript:如何创建一个对象并过滤这些属性? [英] JavaScript: How to create an Object and filter on those attributes?
本文介绍了JavaScript:如何创建一个对象并过滤这些属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的房屋的JavaScript数组,
{
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种不同的搜索方法。
如何返回这个家庭区域数组的一个子集:
- X与Y之间的
价格
浴室 - #
卧室 == A或== B或== C
例如,我将如何创建psuedo代码:
homes.filter {价格> = 150000,价格<= 400000,浴室> = 2.5,卧室== 1 |卧室== 3)
解决方案
基于)内置了 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})等
msie fallback请参阅上面链接的页面。
I have a JavaScript array of houses like so,
{
"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\/"
}],
..........
}
I want to provide 3 different search methods.
How can I return a subset of this homes area array that has:
- The
price
between X and Y - The
bathrooms
>= Z - The # of
bedrooms
== A or == B or == C
For example, how would I create the psuedo code like:
homes.filter {price >= 150000, price <= 400000, bathrooms >= 2.5, bedrooms == 1 | bedrooms == 3}
解决方案
Javascript 1.6 (FF, Webkit-based) has built-in Array.filter function, so there's no need to reinvent the wheel.
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
for a msie fallback see the page linked above.
这篇关于JavaScript:如何创建一个对象并过滤这些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文