与jquery $ .grep混淆

时间:2014-03-22 21:55:42

标签: jquery

我想只显示至少1个位置为yes的名称/描述对(因此不会显示name3 / description 3对),我正在尝试使用grep但它似乎总是返回el而不是我在循环中创建的数组,在返回原因之前temp也是空的?还运行返回3次可能是错误的。

http://jsfiddle.net/7zHP3/295/

var a, b, c;

a = [
    {
    "name": "name",
    "location1": "no",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services"},
{
    "name": "name2",
    "location1": "yes",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services2"},
{
    "name": "name3",
    "location1": "no",
    "location2": "no",
    "location3": "no",
    "location4": "no",
    "location5": "no",
    "description": "description of services3"}
];
b = $.grep(a, function(el, i) {
   var temp = [];
  $.each(el, function( index, value ){
  if(index.indexOf("location") != -1 && value == 'yes')
  {
          temp[el.name]= el;

  }

        });
console.log('returning'+temp);
return temp;


});

1 个答案:

答案 0 :(得分:1)

grep的内部函数应该返回一个布尔值。您正在尝试返回一个数组。

https://api.jquery.com/jQuery.grep/

  

处理每个项目的功能。函数的第一个参数是item,第二个参数是索引。该函数应返回一个布尔值。 this将成为全局窗口对象。

你想要这个:

b = $.grep(a, function(el, i) {
    var found = false;

    $.each(el, function( index, value ){
        found = found || (index.indexOf("location") != -1 && value == 'yes');
    });

    return found;
});

jsFiddle