json对象数组按对象属性排序
Posted hngdlxy143
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json对象数组按对象属性排序相关的知识,希望对你有一定的参考价值。
var staffs=[{name:"join",age:20},{name:"ajax",age:21},{name:"trim",age:22}];
function compare(property){
return function(obj1,obj2){
var value1=obj1[property];
var value2=obj2[property]
return value1-value2;
}
}
var newStaffs=staffs.sort(compare("name"));
console.log(newStaffs)
var array = [
{name: ‘a‘, phone: 1},
{name: ‘a‘, phone: 2},
{name: ‘b‘, phone: 5},
{name: ‘d‘, phone: 3},
{name: ‘c‘, phone: 4}
]
array.sort(getSortFun(‘desc‘, ‘name‘));
function getSortFun(order, sortBy) {
var ordAlpah = (order == ‘asc‘) ? ‘>‘ : ‘<‘;
var sortFun = new Function(‘a‘, ‘b‘, ‘return a.‘ + sortBy + ordAlpah + ‘b.‘ + sortBy + ‘?1:-1‘);
return sortFun;
}
console.log(JSON.stringify(array));
以上是关于json对象数组按对象属性排序的主要内容,如果未能解决你的问题,请参考以下文章