2014-01-15 185 views
6

我有包含名字,姓氏和年齡的json對象數組。我想根據年齡對數組進行排序。基於屬性排序json對象

<!DOCTYPE html> 
<html> 
<body> 
    <h2>Create Object from JSON String</h2> 
    <p>Original name: <span id="origname"></span></p> 
    <p>New name: <span id="newname"></span></p> 
    <p>Age: <span id="age"></span></p> 

    <script> 
    var employees = [ 
     { "firstName" : "John" , "lastName" : "Doe" , "age":"24" }, 
     { "firstName" : "Anna" , "lastName" : "Smith" , "age":"30" }, 
     { "firstName" : "Peter" , "lastName" : "Jones" , "age":"45" }, 
    ]; 

    document.getElementById("origname").innerHTML=employees[0].firstName + " " + employees[0].lastName; 

    // Set new name 
    employees[0].firstName="Gilbert"; 
    document.getElementById("newname").innerHTML=employees[0].firstName + " " + employees[0].lastName; 

    document.getElementById("age").innerHTML=employees[0].age; 
    </script> 
</body> 
</html> 
+0

也許這個答案可以幫助你http://stackoverflow.com/questions/881510/jquery-sorting-json-by-properties –

+0

https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Prinzhorn

+0

檢查此鏈接http://stackoverflow.com/questions/8175093/simple-function-to-sort-a-json-object-using-javascript –

回答

9
function sortByKey(array, key) { 
return array.sort(function(a, b) { 
    var x = a[key]; var y = b[key]; 
    return ((x < y) ? -1 : ((x > y) ? 1 : 0)); 
}); 
} 

people = sortByKey(employees, 'age'); 

console.log(people); 
+2

謝謝,它的工作! – MayurKode

+5

你能解釋一下邏輯嗎? – MayurKode

+0

我喜歡這個解決方案。但是,有沒有辦法讓它訪問該對象的'孫'屬性?例如sortByKey(myArr,'myList.myElement') –