所以,我有这个简单的数据集:
现场演示:http://jsbin.com/ramuwow/edit?js,console
var members = [{
"id": "1",
"firstName": "JOHN",
"lastName": "MARTY"
}, {
"id": "2",
"firstName": "JONES",
"lastName": "SMITH"
}, {
"id": "3",
"firstName": "MARY",
"lastName": "DOE"
}, {
"id": "4",
"firstName": "MARGARET",
"lastName": "KANE"
}];
我从输入中得到一个字符串来搜索这些对象。
我可以从姓名到姓名。但我不能做第一个和姓氏。
这是我到目前为止所拥有的:
var members = [{"id":"1","firstName":"JOHN","lastName":"MARTY"},{"id":"2","firstName":"JONES","lastName":"SMITH"},{"id":"3","firstName":"MARY","lastName":"DOE"},{"id":"4","firstName":"MARGARET","lastName":"KANE"}];
var filteredNames = members.filter(function(n){
var query = "MARY DO";
var splitUp = query.split(" ");
console.log(splitUp);
return n.firstName.indexOf(query) > -1 ? n : false ||
n.lastName.indexOf(query) > -1 ? n : false ||
n.id.indexOf(query) > -1 ? n : false ||
n.firstName.indexOf(splitUp[0]) > -1 && n.lastName.indexOf(splitUp[1]);
});
console.log(filteredNames);
然后返回:
["MARY", "DO"]
["MARY", "DO"]
["MARY", "DO"]
["MARY", "DO"]
[]
我做错了什么? MARY DOE
的对象应该出现。
答案 0 :(得分:1)
问题:您最后错过了与-1
的比较。
解决方案:
将最后一个与-1
进行比较,您将获得对象:
var members = [{"id":"1","firstName":"JOHN","lastName":"MARTY"},{"id":"2","firstName":"JONES","lastName":"SMITH"},{"id":"3","firstName":"MARY","lastName":"DOE"},{"id":"4","firstName":"MARGARET","lastName":"KANE"}];
var filteredNames = members.filter(function(n){
var query = "MARY DO";
var splitUp = query.split(" ");
console.log(splitUp);
return n.firstName.indexOf(query) > -1 ? n : false ||
n.lastName.indexOf(query) > -1 ? n : false ||
n.id.indexOf(query) > -1 ? n : false ||
n.firstName.indexOf(splitUp[0]) > -1 && n.lastName.indexOf(splitUp[1] > -1);
});
console.log(filteredNames);
输出:
["MARY", "DO"]
["MARY", "DO"]
["MARY", "DO"]
["MARY", "DO"]
[[object Object] {
firstName: "MARY",
id: "3",
lastName: "DOE"
}]
@Credit转到@ Pointy