Jquery按多个属性和值

时间:2017-12-14 13:02:14

标签: javascript jquery arrays object

我有一个多选择框,我尝试根据所选的多重属性来获取过滤后的数据 就像这个例子

var names = [
    { name : "Joe", age:20, email: "joe@hotmail.com"},
    { name : "Mike", age:50, email: "mike@hotmail.com"},
    { name : "Joe", age:45, email: "mike@hotmail.com"}
   ];

var filteredNames = $(names).filter(function( idx ) {
    return names[idx].name === "Joe" && names[idx].age < 30;
}); 

但在我的情况下,我想按值数组过滤

 // data selected
var nameselected= $('select[name="usernames"]').val();
var ageselected= $('select[name="ages"]').val();
var filteredNames = $(names).filter(function( idx ) {
    return names[idx].name IN ( nameselected ) && names[idx].age IN (ageselected);
}); 

我能做到吗!

2 个答案:

答案 0 :(得分:1)

我认为您可以使用indexOf(结果值&gt; -1,如果值在数组中)来检查您的数据值是否在所选值的数组中

请参阅beloow代码:

var names = [
    { name : "Joe", age:20, email: "joe@hotmail.com"},
    { name : "Mike", age:50, email: "mike@hotmail.com"},
    { name : "Joe", age:45, email: "mike@hotmail.com"},
    { name : "Doe", age:40, email: "doe@hotmail.com"}
   ];

var nameselected = ["Joe","Doe"];
var ageselected =  [20,40,35];

var filteredNames = $(names).filter(function( idx ) {
    return (nameselected.indexOf(names[idx].name)>-1 && ageselected.indexOf(names[idx].age)>-1);
}); 

$.each(filteredNames,function(index,name){
  console.log(name);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

如果您要过滤selectednames数组中selectedages数组和年龄的所有项目,您可以执行以下操作:

var filteredNames = names.filter(function(item) {
  return nameselected.indexOf(item.name) > -1 && ageselected.indexOf(item.age) > -1;
});

<强>演示:

&#13;
&#13;
var names = [{
    name: "Joe",
    age: 20,
    email: "joe@hotmail.com"
  },
  {
    name: "Mike",
    age: 50,
    email: "mike@hotmail.com"
  },
  {
    name: "John",
    age: 45,
    email: "mike@hotmail.com"
  }
];

//var nameselected= $('select[name="usernames"]').val();
//var ageselected= $('select[name="ages"]').val();

var nameselected = ["Joe", "John"];
var ageselected = [20, 45];

var filteredNames = names.filter(function(item) {
  return nameselected.indexOf(item.name) > -1 && ageselected.indexOf(item.age) > -1;
});

console.log(filteredNames);
&#13;
&#13;
&#13;

注意:

  • 请注意,最好使用Javascript Array函数循环遍历数组,而不是使用jQuery方法并使事情复杂化。

  • 请注意,这只会返回年龄为selectedages的项目 在这种情况下,数组,而不是低于selectedages值的年龄 您需要对array年龄进行排序以检查该项目 低于最低值。