过滤JSON数据

gan*_*esh 13 javascript json

我有一个JSON文件,其中包含如下数据:

{"posts": [ 
    { "title":"1", "url":"n1.png" }, 
    { "title":"2", "url":"n2.png" }, 
    { "title":"3", "url":"n3.png" }, 
    { "title":"4", "url":"n4.png" }, 
    { "title":"5", "url":"n5.png" }, 
    { "title":"6", "url":"n6.png" }, 
    { "title":"7", "url":"n7.png" }, 
    { "title":"8", "url":"n8.png" }, 
    { "title":"9", "url":"n9.png" }, 
    { "title":"10", "url":"n10.png" },
]}
Run Code Online (Sandbox Code Playgroud)

我需要用两个文本框按范围过滤标题:从和到.

Rod*_*ist 39

为什么不这样做?

var json = JSON.parse('{"posts": [ 
{ "title":"1", "url":"n1.png" }, 
{ "title":"2", "url":"n2.png" }, 
{ "title":"3", "url":"n3.png" }, 
{ "title":"4", "url":"n4.png" }, 
{ "title":"5", "url":"n5.png" }, 
{ "title":"6", "url":"n6.png" }, 
{ "title":"7", "url":"n7.png" }, 
{ "title":"8", "url":"n8.png" }, 
{ "title":"9", "url":"n9.png" }, 
{ "title":"10", "url":"n10.png" }
]}');

var filteredJson = json.posts.filter(function (row) {
  if(row.title matches your criteria) {
    return true
  } else {
    return false;
  }
});
Run Code Online (Sandbox Code Playgroud)

是的,它是一个ES5方法,但可以非常好地填充

  • +1不立即链接到库来处理不需要的东西 (11认同)

JCo*_*ine 9

我在我当前的项目中使用Linq JS,它非常适合过滤数据.

http://jslinq.codeplex.com/

var posts = [ 
    { "title":"1", "url":"n1.png" }, 
    { "title":"2", "url":"n2.png" }, 
    { "title":"3", "url":"n3.png" }, 
    { "title":"4", "url":"n4.png" }, 
    { "title":"5", "url":"n5.png" }, 
    { "title":"6", "url":"n6.png" }, 
    { "title":"7", "url":"n7.png" }, 
    { "title":"8", "url":"n8.png" }, 
    { "title":"9", "url":"n9.png" }, 
    { "title":"10", "url":"n10.png" }
];

var filteredPost = JSLINQ(posts)
                   .Where(function(item){ return item.title >= "textBox1Value" && item.title <= "textBox2Value"; });
Run Code Online (Sandbox Code Playgroud)