2016-05-12 20 views
1

對於一所學校,我正在創建一個使用JSON和JavaScript將數據拉回到網頁的程序。我知道如何對數組進行排序並將它們的值拉回來。讓我說我有這個JSON。如何使用網頁中的多個不同參數對JSON進行排序?

{"name":"Michael","age":30,"bday":"05/12/1982"} 
{"name":"Andy", "age":30,"bday":"02/21/1992"} 
{"name":"Justin", "age":19,"bday":"12/07/1972"} 

我怎麼能有一個名字輸入,年齡選擇並正在使用的生日輸入,我可以通過這些的任意組合進行排序。

說出30歲出生於1990年2月21日的每個人,或每個30歲的人?我希望能夠按照每種可能的數據輸入組合進行排序,並且我不想僅使用一堆if()語句。

+3

你想排序或篩選? –

+0

是你將這些數據顯示到數據表中的表格,還是你需要這些數據? – C2486

+0

對不起,我想這將根據用戶在網頁UI上選擇的選項進行過濾。我將只顯示回網頁 – RainMan

回答

1

該算法查找search中的每個屬性,如果全部比較均爲真,則將該元素添加到結果集中。

function filter(array, search) { 
 
    return array.filter(function (a) { 
 
     return Object.keys(search).every(function (k) { 
 
      return (
 
       a[k] === search[k] || 
 
       typeof search[k] === 'object' && +search[k].min <= a[k] && a[k] <= +search[k].max || 
 
       typeof search[k] === 'function' && search[k](a[k]) 
 
      ); 
 
     }); 
 
    }); 
 
} 
 

 
var data = [{ name: "Michael", age: 30, bday: "05/12/1982" }, { name: "Andy", age: 30, bday: "02/21/1992" }, { name: "Justin", age: 19, bday: "12/07/1972" }]; 
 

 
// serach for name with n 
 
document.write('<pre>' + JSON.stringify(filter(data, { name: function (s) { return s.match(/n/i); } }), 0, 4) + '</pre>'); 
 

 
// search for age = 30 
 
document.write('<pre>' + JSON.stringify(filter(data, { age: 30 }), 0, 4) + '</pre>'); 
 

 
// search for age = 30 and bday = 02/21/1992 
 
document.write('<pre>' + JSON.stringify(filter(data, { age: 30, bday: '02/21/1992' }), 0, 4) + '</pre>'); 
 

 
// search for age between 18 and 20 
 
document.write('<pre>' + JSON.stringify(filter(data, { age: { min: 18, max: 20} }), 0, 4) + '</pre>');

+1

謝謝你先生是awsome! – RainMan

1

你可以輸入在烏拉圭回合的HTML文件filtring信息

<input type="search" id="search" placeholder="search"> 

和JS文件中像這樣

$("#search").keyup(function() { 
var searchField = $("#search").val(); 
// RegExp for case sensitive 
var myReg = new RegExp(searchField,"i"); 
$.getJSON('data.json',function (data) { 
    var output ="<ul class='searchresults'>"; 
    $.each(data,function(key,val){ 
     if((val.name.search(myReg) != -1) || (val.info.search(myReg) != -1)){ 

      output +='<li>'; 
      output += "<h2>"+val.name+"</h2>"; 
      output += "<p>"+val.age+"</p>"; 
      output+='</li>'; 
     } 
    }); 
    output +='</ul>'; 
    $("#update").html(output) 
}); 

});

相關問題