js对象排序or数组排序(基于排序相同的属性之外再次排序其他的属性)
作者:互联网
//对象排序 var obj = { 0:{name:'小红',age:'18',inset:'吃饭'}, 1:{name:'小狗',age:'16',inset:'游泳'}, 2:{name:'小黄',age:'14',inset:'睡觉'}, 3:{name:'小光',age:'12',inset:'看电视'}, 4:{name:'小黄',age:'8',inset:'睡觉'}, 5:{name:'小明',age:'15',inset:'玩电脑'}, 6:{name:'小光',age:'6',inset:'看电视'}, } var sb = JSON.parse(JSON.stringify(obj)) var sortedObjKeys = Object.keys(sb).sort(function(a, b){ if(sb[a]['inset']!= sb[b]['inset']){ return sb[a]['inset'].localeCompare(sb[b]['inset'],'zh'); //最先inset属性值不相同时排序 } if(sb[a]['name']!= sb[b]['name']){ return sb[a]['name'].localeCompare(sb[b]['name'],'zh'); //基于inset属性值相同的情况下 再根据name排序 } return sb[a].age - sb[b].age //最后基于name值相同时再根据age排序 }); for( var key in sortedObjKeys){ obj[key] = sb[sortedObjKeys[key]] } console.log(obj) //数组排序 var arr = [ {name:'小红',age:'18',inset:'吃饭'}, {name:'小狗',age:'16',inset:'游泳'}, {name:'小黄',age:'14',inset:'睡觉'}, {name:'小光',age:'12',inset:'看电视'}, {name:'小黄',age:'8',inset:'睡觉'}, {name:'小明',age:'15',inset:'玩电脑'}, {name:'小光',age:'6',inset:'看电视'}, ] arr.sort(function(a, b){ if(a['inset']!= b['inset']){ return a['inset'].localeCompare(b['inset'],'zh'); //最先inset属性值不相同时排序 } if(a['name']!= b['name']){ return a['name'].localeCompare(b['name'],'zh'); //基于inset属性值相同的情况下 再根据name排序 } return a.age - b.age //最后基于name值相同时再根据age排序 }); console.log(arr)
标签:return,name,age,js,inset,sb,排序,属性 来源: https://www.cnblogs.com/MJ-MY/p/11897809.html