2012-02-28 2 views
12

나는 다음과 같은 데이터가 포함 된 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" }, 
]} 

:까지합니다.

+5

시작하려면 배열이 유효하지 않습니다. 마지막 쉼표를 제거하십시오. –

+1

더 많은 정보를 제공해야합니다 ... 범위가 포함되어 있습니까? 제목에 대한 값은 항상 문자열로 전달되는 숫자입니까? – scunliffe

+0

질문이 명확하지 않습니다. jsfiddle/jsbin에서 데모를 만드십시오. 문제를 명확히하십시오. –

답변

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"; }); 
1

json을 jquery (http://api.jquery.com/jQuery.parseJSON/)의 parseJson 함수/object로 읽어 들여 splice 함수를 사용하여 배열을 연결하려고합니다() 물체를 결합하고 그 물체를 접합하십시오.

+1

나는 향신료 기능을 좋아합니다. 너무 맛있어. – joidegn

38

이 왜하지?

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 방법하지만 아주 잘

+9

+1을 필요로하지 않는 것들을 처리하기 위해 라이브러리에 바로 연결하지 않기 때문에. – Snuffleupagus

+0

많은 사람들이 4-5 라인 픽스에 30-60kb 라이브러리가 필요하다고 생각하고 있습니다. –

+1

좋은 예입니다. JSON이 아니므로 var filterJson = json.posts.filter (... filterJson은 일치하는 행의 배열이므로 filterJson [2]는 필터와 일치하는 세 번째 항목입니다 – Dave

2

shimmed 수있는 노력이

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

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

이 또 다른 해결책이있다 : 사용 jLinq.js (documentation), 더있다 풍모. 이 경우, 다음과 같은 코드를 사용하여 솔루션을 얻을 수 있습니다 : 당신은 모든 JSON 데이터를 일단

var selectedPosts = jLinq.from(posts) 
         .betweenEquals("title",4,8) 
         .select(); 
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> 
0

첫째, 당신이 그들을 통과해야합니다. 이를 위해,

  **$.each(data, function (i, data) { 
      if (data.title >= "textBox1Value" && item.title <= "textBox2Value") 
      //then the data; 
     });** 
  1. 목록 항목
0

글쎄, 프로젝트의 각 제품에 속하는 프로젝트의 전체이 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; 
}