我有json对象数组包含firstname,lastname和age.我想根据年龄对数组进行排序.
<!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>
解决方法
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);