JavaScript的。按多个属性过滤对象

时间:2016-05-15 23:28:47

标签: javascript

所以,我有这个简单的数据集:

现场演示: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的对象应该出现。

1 个答案:

答案 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

JSBin链接: http://jsbin.com/geziwetudi/edit?js,console