我有一个示例json数组,其中包含employeeId的列表
[{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}]
希望获得最后一个employeeId":"20180000003
$.ajax({
url:'api/applicants/getwatchers',
type:'GET',
success: function(data){
watcherId = (data[data.length-1].employeeId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);
}
});
但是console.log是employeeId": "20180000000
答案 0 :(得分:3)
希望得到最后一个id为employeeId":" 20180000003
通过 last id ,如果您的意思是最大ID (由系统最后生成),则使用Math.max.apply
和map
var arr = [{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}];
watcherId = Math.max.apply( null, arr.map( s => +s.employeeId ) );
watcherId
已经是Number
,无需执行parseInt
,因此newWatcherId变为
newWatcherId = watcherId + 1;
答案 1 :(得分:0)
如果要获取最大数字,则需要在获取最后一个元素之前对数组进行排序。
$.ajax({
url:'api/applicants/getwatchers',
type:'GET',
success: function(data){
data.sort((a,b) => b.employeeId - a.employeeId)
watcherId = (data[data.length-1].employeeId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);
}
});
我有可能倒退 - 我总是这样做哈哈。在这种情况下尝试:
data.sort((a,b) => a.employeeId - b.employeeId)
答案 2 :(得分:0)
您可以按降序对数组进行排序,然后获取第一个数组,如下所示:
list = [{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}];
sortedIds = list.map(emp => emp.employeeId) // map the array to empIds.
.sort((a, b) => b - a)[0]; // sort desc.
lastId = sortedIds[0];
答案 3 :(得分:0)
使用点差运算符在Math.max()
数组上使用employeeId
。
var maxId = Math.max(...data.map(el=>el. employeeId)); // Will give you the max ID
watcherId = (maxId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);