<script>
// function fn(data){
// alert(data);
// }
var arr=[{id:1,name:'1菜单'},{id:3,name:'3菜单'},{id:2,name:'2菜单'},{id:6,name:'6菜单'},{id:4,name:'4菜单'},{id:5,name:'5菜单'}]
function sortId(x,y) {
return x.id-y.id;
}
// console.log(arr.sort(sortId));
result=arr.sort(sortId);
console.log(result);
</script>
js 实现json对象根据数组排序
已知有一下格式的json数据
var arr={
A:'11111',
B:'22222',
C:'33333',
D:'44444'
}
和一个包含arr的key的有序数组
var arrIdx=[C,B,D,A];
现在希望arr对象根据arrIdx的顺序排序,得到新的对象
var arr={
C:'33333',
B:'22222',
D:'44444',
A:'11111'
}
求一个高效的 简洁的写法!
案例下面:
const obj = {
A:'11111',
B:'22222',
C:'33333',
D:'44444'
};
const arrIdx = ['C','B','D','A'];
let ret = {};
arrIdx.forEach((item, index) => {
ret[arrIdx[index]] = obj[item]
});
console.log(ret)
————————————————————————————————————
js 按照数组json数据中的日期排序
var data = {
"rows": [{
"name": "张三",
"time": "2011/4/1 0:00:00",
},{
"name": "李四",
"time": "2015/5/6 12:30:00",
},{
"name": "王五",
"time": "2012/10/1 22:10:00",
},{
"name": "赵六",
"time": "2011/9/1 22:10:00",
}]
};
var rows = data.rows;
rows.sort(function(a,b){
return Date.parse(a.time) - Date.parse(b.time);//时间正序
});
for(var i =0,l=rows.length;i
console.log(rows[i].name + " | " + rows[i].time);
}
网友评论