根据条件选择JSon对象

Select JSon objects based on criteria

本文关键字:JSon 对象 选择 条件      更新时间:2024-03-18

我正在过滤一个大型json数据集,我想知道如何垂直选择json对象。

Lat以这个小例子为例,我想选择所有作者名字包含"Evelyn"的书

data= [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price":8
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 8
      },
      { "category": "fiction",
        "author": "Evelyn Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }

结果我应该得到:

  { "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 8
          },
          { "category": "fiction",
            "author": "Evelyn Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
          },

我可以这样做吗:

$.each(data,function(i,el)
{
    var newdata;
     if (data.author.contains('Evelyn')) newdata.push()
});

另一种方式:

 data.where( "( n, i ) => n.author.contains('Evelyn') " ) ;

你知道这两种方法的问题在哪里吗?由于我有一个庞大的数据集,解决这个问题的最快方法是什么?

您可以使用Array.filter:

var filtered = data.filter(function(a){return +(a.price) >= 8;}

或过滤author字段:

var filtered = data.filter(function(a){return /evelyn/i.test(a.author);});
// now [filtered] contains the objects from [data] 
// where 'author' contains 'Evelyn'
// filtered.length => 2
// filtered[0].category => 'fiction'

MDN过滤器文档(包括旧浏览器的填充程序)

你试过这个吗?我已经在我的一些项目中使用过它,真的可以推荐它。http://www.hugoware.net/projects/jlinq

您可以使用filter:

data.filter(function(book) {
  return /Evelyn/.test(book.author);
});

contains运算符在这里不起作用,您必须在这里使用indexOf函数。下面的代码应该工作良好

data= [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price":8
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 8
      },
      { "category": "fiction",
        "author": "Evelyn Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }];
data.forEach(function(args){
    if(args.author.indexOf('Evelyn') >= 0){
        console.log(args);
    }
});