JGr*_*eig 424 javascript jquery
我有以下JavaScript数组的房地产家庭对象:
var json = {
'homes': [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
// ... (more homes) ...
]
}
var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;
Run Code Online (Sandbox Code Playgroud)
我想要做的是能够对对象执行过滤器以返回"home"对象的子集.
例如,我想基于对能够过滤:price,sqft,num_of_beds,和num_of_baths.
问题:如何在JavaScript中执行某些操作,如下面的伪代码:
var newArray = homes.filter(
price <= 1000 &
sqft >= 500 &
num_of_beds >=2 &
num_of_baths >= 2.5 );
Run Code Online (Sandbox Code Playgroud)
注意,语法不必与上面完全相同.这只是一个例子.
CMS*_*CMS 646
您可以使用以下Array.prototype.filter方法:
var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});
Run Code Online (Sandbox Code Playgroud)
实例:
var obj = {
'homes': [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
// ... (more homes) ...
]
};
// (Note that because `price` and such are given as strings in your object,
// the below relies on the fact that <= and >= with a string and number
// will coerce the string to a number before comparing.)
var newArray = obj.homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >= 2 &&
el.num_of_baths >= 1.5; // Changed this so a home would match
});
console.log(newArray);Run Code Online (Sandbox Code Playgroud)
此方法是新ECMAScript第5版标准的一部分,几乎可以在所有现代浏览器中找到.
对于IE,您可以包含以下方法以实现兼容性:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i];
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Run Code Online (Sandbox Code Playgroud)
Rut*_*ani 28
您可以尝试使用类似jLinq的框架 - 以下是使用jLinq的代码示例
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请访问http://www.hugoware.net/projects/jlinq链接
小智 28
我很惊讶没有人发布单行回复:
const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);
Run Code Online (Sandbox Code Playgroud)
...这样您就可以更轻松地阅读它:
const filteredHomes = json.homes.filter( x =>
x.price <= 1000 &&
x.sqft >= 500 &&
x.num_of_beds >=2 &&
x.num_of_baths >= 2.5
);
Run Code Online (Sandbox Code Playgroud)
Jul*_*sar 25
我更喜欢Underscore框架.它建议对象有许多有用的操作.你的任务:
var newArray = homes.filter(
price <= 1000 &
sqft >= 500 &
num_of_beds >=2 &
num_of_baths >= 2.5);
Run Code Online (Sandbox Code Playgroud)
可以覆盖像:
var newArray = _.filter (homes, function(home) {
return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;
});
Run Code Online (Sandbox Code Playgroud)
希望它对你有用!
kin*_*neo 14
使用过滤器
var json = {
homes: [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
]
}
let filter =
json.homes.filter(d =>
d.price >= 1000 &
d.sqft >= 500 &
d.num_of_beds >=2 &
d.num_of_baths >= 2.5
)
console.log(filter)Run Code Online (Sandbox Code Playgroud)
Che*_*yDT 12
这个问题是在考虑到多个结果的情况下提出的,在这种情况下filter就是要走的路,正如这里的其他回答者已经指出的那样。
然而,由于这个问题已经成为一个流行的重复目标,我应该提到,如果您只是寻找满足条件的单个元素,则不需要filter并且可以使用find. 它的工作方式相同,但它只是返回第一个匹配元素,或者undefined如果没有元素匹配,而不是返回匹配数组:
const data = [
{ id: 1, value: 10 },
{ id: 2, value: 20 },
{ id: 3, value: 30 }
]
console.log(data.filter(o => o.value > 15))
// Output: [{ id: 2, value: 20 }, { id: 3, value: 30 }]
console.log(data.find(o => o.value > 15))
// Output: { id: 2, value: 20 }
console.log(data.filter(o => o.value > 100))
// Output: []
console.log(data.find(o => o.value > 100))
// Output: undefined
// `find` is often useful to find an element by some kind of ID:
console.log(data.find(o => o.id === 3))
// Output: { id: 3, value: 30 }
Run Code Online (Sandbox Code Playgroud)
小智 9
这是使用jquery MAP功能在IE8中正常工作的工作小提琴
http://jsfiddle.net/533135/Cj4j7/
json.HOMES = $.map(json.HOMES, function(val, key) {
if (Number(val.price) <= 1000
&& Number(val.sqft) >= 500
&& Number(val.num_of_beds) >=2
&& Number(val.num_of_baths ) >= 2.5)
return val;
});
Run Code Online (Sandbox Code Playgroud)
你可以很容易地做到这一点 - 可能有很多实现你可以选择,但这是我的基本想法(并且可能有一些格式你可以用jQuery迭代一个对象,我现在不能想到它):
function filter(collection, predicate)
{
var result = new Array();
var length = collection.length;
for(var j = 0; j < length; j++)
{
if(predicate(collection[j]) == true)
{
result.push(collection[j]);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后您可以像这样调用此函数:
filter(json, function(element)
{
if(element.price <= 1000 && element.sqft >= 500 && element.num_of_beds > 2 && element.num_of_baths > 2.5)
return true;
return false;
});
Run Code Online (Sandbox Code Playgroud)
这样,您可以根据您定义的任何谓词调用过滤器,甚至可以使用较小的过滤器多次过滤.
你可以使用jQuery.grep(),因为jQuery 1.0:
$.grep(homes, function (h) {
return h.price <= 1000
&& h.sqft >= 500
&& h.num_of_beds >= 2
&& h.num_of_baths >= 2.5
});
Run Code Online (Sandbox Code Playgroud)
const y = 'search text';
const a = [{key: "x", "val: "y"}, {key: "d", "val: "z"}]
const data = a.filter(res => {
return(JSON.stringify(res).toLocaleLowerCase()).match(y.toLocaleLowerCase());
});
Run Code Online (Sandbox Code Playgroud)
我使用ruleOut函数根据特定的不需要的属性值过滤对象。我知道在您的示例中您想使用条件而不是值,但我的答案对于问题标题有效,所以我想将我的方法留在这里。
function ruleOut(arr, filterObj, applyAllFilters=true) {
return arr.filter( row => {
for (var field in filterObj) {
var val = row[field];
if (val) {
if (applyAllFilters && filterObj[field].indexOf(val) > -1) return false;
else if (!applyAllFilters) {
return filterObj[field].filter(function(filterValue){
return (val.indexOf(filterValue)>-1);
}).length == 0;
}
}
}
return true;
});
}
Run Code Online (Sandbox Code Playgroud)
假设你有一个这样的演员列表:
let actors = [
{userName:"Mary", job:"star", language:"Turkish"},
{userName:"John", job:"actor", language:"Turkish"},
{userName:"Takis", job:"star", language:"Greek"},
{userName:"Joe", job:"star", language:"Turkish"},
{userName:"Bill", job:"star", language:"Turkish"}
];
Run Code Online (Sandbox Code Playgroud)
你想找到所有被评为好莱坞明星的演员,他们的国籍不应该是“英国”、“意大利”、“西班牙”、“希腊”之一,而且他们的名字也不应该是“玛丽”之一, ‘乔’。奇怪的例子,我知道!无论如何,根据这组条件,您将创建以下对象:
let unwantedFieldsFilter= {
userName: ['Mary', 'Joe'],
job: ['actor'],
language: ['English', 'Italian', 'Spanish', 'Greek']
};
Run Code Online (Sandbox Code Playgroud)
好吧,现在如果你ruleOut(actors, unwantedFieldsFilter)只想得到
[{用户名:“比尔”,工作:“明星”,语言:“土耳其语”}]
而比尔就是你的男人,因为他的名字不是“玛丽”、“乔”之一,他的国籍也不包含在[“英语”、“意大利语”、“西班牙语”、“希腊语”]中,而且他是一个明星!
我的方法中有一个选项,即applyAllFilters默认情况下为 true。如果您尝试将此参数设置为 false 来进行排除,则这将用作“OR”过滤而不是“AND”。示例:ruleOut(actors, {job:["actor"], language:["Italian"]}, false)将为您找到除演员或意大利人之外的所有人:
[{userName: "Mary", job: "star", language: "Turkish"},
{userName: "Takis", job: "star", language: "Greek"},
{userName: "Joe", job: "star",语言:"土耳其语"},
{用户名:"Bill",工作:"star",语言:"土耳其语"}]
| 归档时间: |
|
| 查看次数: |
648625 次 |
| 最近记录: |