js数组对象排序
项目中遇到每次重启设备 tab标题随机显示,用户体验不好,于是需要排序,使得每次都按一定的顺序显示,直接上源码,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>数组对象排序</title>
</head>
<body>
<script>
var objs = [
{ isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalATVSIP',
header: 'ATVSIP'
},
{ isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalATVTurn',
header: 'ATVTurn'
},
{
isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalFseyeOrDeviceID',
header: 'DeviceID',
},
{
isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalGB28181',
header: 'GB28181',
},
{
isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalGB35114',
header: 'GB35114',
},
{
isActive: true,
isDisabled: false,
isVisible: true,
hash: 'CVConfigProtocalI8S',
header: 'I8S',
},
];
objs.sort(function (a, b) {
// order是规则 objs是需要排序的数组
var order = ['DeviceID', 'GB28181', 'I8S', 'ATVTurn', 'ATVSIP', 'GB35114'];
return order.indexOf(a.header) - order.indexOf(b.header);
});
// 根据规则排序后新的数组
var result = objs.map(function (a) {
return a['hash'];
});
console.log('Current order is: ' + result.join(', '), 'result: ' + result);
//==> CVConfigProtocalFseyeOrDeviceID,
// CVConfigProtocalGB28181,
// CVConfigProtocalI8S,
// CVConfigProtocalATVTurn,
// CVConfigProtocalATVSIP,
// CVConfigProtocalGB35114
//项目中使用
Sort_protocal(arr) {
msg("arr",arr)
let objs = arr;
// order是规则 objs是需要排序的数组
let order = ['DeviceID', 'GB28181', 'I8S', 'ATVTurn', 'ATVSIP', 'GB35114'];
objs.sort((a, b) => {
return order.indexOf(a.header) - order.indexOf(b.header);
});
let templist = [];
for (let key in objs) {
templist.push({
isActive: objs[key].isActive,
isDisabled: objs[key].isDisabled,
isVisible: objs[key].isVisible,
hash: objs[key].hash,
header: objs[key].header,
});
}
this.subtabs = templist;
},
</script>
</body>
</html>