过滤JSON数据

时间:2012-02-28 14:26:29

标签: 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" },
]}

我需要使用两个文本框按范围过滤 title :from和to。

8 个答案:

答案 0 :(得分: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;
  }
});

是的,它是一种ES5方法,但可以很好地填充

答案 1 :(得分: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"; });

答案 2 :(得分:2)

试试这个

var q = new RegExp(req.query.q,'i');

posts = posts.filter(function(item){
    if(item.title.match(q) || item.url.match(q)){
        return item;
    }
});

答案 3 :(得分:2)

还有另一个解决方案:使用jLinq.jsdocumentation),它具有更多功能。在这种情况下,您可以使用以下代码获得解决方案:

var selectedPosts = jLinq.from(posts)
                         .betweenEquals("title",4,8)
                         .select();

答案 4 :(得分:1)

将json读入对象/ arr jquery的parseJson函数(http://api.jquery.com/jQuery.parseJSON/)并尝试使用splice函数拼接数组()只需复制一个对象和拼接那个。

答案 5 :(得分:1)

我有这个充满项目的JSON数组,每个项目都属于一个产品:

[
 {
    "id": 1,
    "parentProduct": {
      "id": 12,
      "productName": "Test 123"
    },
    "phase": "Phase 4",
    "productNumber": "111223",
    "projectName": "Test JPEG Apple",
    "supplier1": "de",
  },
  {
   "id": 2,
   "parentProduct": {
     "id": 12,
     "productName": "Test from me"
   },
   "phase": "222",
   "productNumber": "11122",
   "projectName": "Test PNG",
   "supplier1": "222"
   }
]

我想只获得具有特定父ID的人,我按以下方式执行:

filterByProductId(projects, productId) : any[] {
    var filteredArray = new Array;
    for(var k in projects) {
      if(projects[k].parentProduct.id == productId) {
        filteredArray.push(projects[k]);
      }
    }
 return filteredArray;
}

答案 6 :(得分:0)

json data array of objects filter



 <html>
    <head>
    <script type="text/javascript">
    /*
        var ss = JOSN.stringify(obj,function(key,value){ //serialization
            if(key=='a'){
                return undefined;
            }else{
                return value;
            }
        });
    */
    var jsonStr = [
    {
    "name": "Bang Bang",
    "outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
    "rating": 5.6,
    "director": "Siddharth Anand",
    "id": 250
    },
    {
    "name": "Bang Bang",
    "outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
    "rating": 5.6,
    "director": "Siddharth Anand",
    "id": 250
    },
    {
    "name": "Bang Bang",
    "outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
    "rating": 5.6,
    "director": "Siddharth Anand",
    "id": 250
    },
    {
    "name": "Indian",
    "outline": "After his daughter's tragic death, a freedom fighter steps up his war against corruption.",
    "rating": 8.4,
    "director": "Shankar",
    "id": 251
    },
    {
    "name": "Dilwale Dulhania Le Jayenge",
    "outline": "Raj and Simran meet on a trip to Europe. After some initial misadventures, they fall in love. The battle begins to win over two traditional families.",
    "rating": 8.4,
    "director": "Aditya Chopra",
    "id": 253
    }
    ];



    var jsonobj = jsonStr;
    function filterMovieDirectorData(movie,director){
        if(movie!='' && (director!='' && director!='Director')){
            var data = jsonobj.filter(function(item){
            return (item["name"].toLowerCase().indexOf(movie.toLowerCase())!=-1 && item["director"].toLowerCase().indexOf(director.toLowerCase())!=-1)
            });
        }else if(movie!='' && director=='Director'){
            var data = jsonobj.filter(function(item){
            return item["name"].toLowerCase().indexOf(movie.toLowerCase())!=-1
            });
        }else if(movie=='' && (director!='' && director!='Director')){
            var data = jsonobj.filter(function(item){
            return item["director"].toLowerCase().indexOf(director.toLowerCase())!=-1
            });
        }

    return data;
    }


    function getFilterDirectorJson(){

        var inputStr = document.getElementById("movie").value;
        var e = document.getElementById("director");
        var directorStr = e.options[e.selectedIndex].text;

        if( (inputStr=='' || inputStr=='Enter movie name') && (directorStr=='' || directorStr=='Director') ){
            alert("Please enter movie name or select director.");
            document.getElementById("filter_data_div").innerHTML="";
            document.getElementById("movie").focus();
            return false;
        }

        var filterObjs = filterMovieDirectorData(inputStr,directorStr); 
        var text="";    
        for(var i=0; i<filterObjs.length; i++){
            text+='<div id="filter_data"><div><h3>'+filterObjs[0].name+'</h3></div>';
            text+='<div>Director : '+filterObjs[0].director+'</div></div><div class="clear"></div>';
        } 
    if(filterObjs.length===0){document.getElementById("filter_data_div").innerHTML='<div id="filter_data"><div><h3>No movies found.</h3></div></div>';}else
    document.getElementById("filter_data_div").innerHTML=text;

    }

    window.onload=function(){   
    getDirectors();
    }

    function getDirectors(){
        for(var i=0; i<jsonobj.length; i++){
            //console.log(jsonobj[i].director);
            var option = document.createElement("option");
            option.text = jsonobj[i].director;
            option.value = i;
            var daySelect = document.getElementById('director');
            daySelect.appendChild(option);      
        }
    }

    </script>
    <style>
    #director{
    line-height: 3px;
    padding: 20px;
    font-size: 21px;
    color: #acacac;
    }
    #go{
    background: #FFC000;
    padding: 11px 14px 16px 11px;
    font-size: 36px;
    line-height: 3;
    color: #fff;
    margin: 0px;
    text-align: center;
    }
    #movie{
    width: 213px;
    font-size: 21px;
    margin-left: 12px;
    padding: 20px;
    color:#ACACAC;
    }
    #main_div{
    background: #EEEEEE;
    width: 554px;
    min-height:120px;
    }
    #filter_data{
    width: 335px;
    background: #D8D8D8;
    padding: 1px 0px 20px 13px;
    margin: 20px 0px 0px 12px;
    border: 1px solid #000;
    }
    a{text-decoration:none;}
    .clear{clear: both;}
    </style>
    </head>
    <body>

    <div id="main_div">
    <div style="display:block;">
    <input type="text" id="movie" placeholder="Enter movie name">
    <select id="director" ><option value="">Director</option></select>
    <a href="javascript:;" id="go" onclick="getFilterDirectorJson(event)">Go</a>
    </div>
    <div id="filter_data_div"></div>
    </div>
    </body>
    </html>

答案 7 :(得分:0)

首先,如果您拥有所有json数据,则需要遍历它们。为此,

         **$.each(data, function (i, data) {
             if (data.title >= "textBox1Value" && item.title <= "textBox2Value")
             //then the data;
         });**
  1. 列表项