我正在使用node.js,express.js构建REST API,但使用数据结构(首先没有数据库)来实现它。我有2条路线Post
和Get
。我的问题是,我该如何实现get
路线,以便能够检索具有作为参数传递的最多技能集的候选人:
这是我的对象
const candidate = [
{"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
{"id":2, "name":"Mary", "skills":["Go","Python"]},
{"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
]
这是get
路线:
app.get('candidate/search', function(res,res){
})
请帮助
答案 0 :(得分:2)
您可以按技能对候选人进行排序,然后使用res.json函数返回最熟练的候选人。
skillSortFunction将按技能数降序排序,因此我们要选择排序数组的第一个元素。
const candidate = [
{"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
{"id":2, "name":"Mary", "skills":["Go","Python"]},
{"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
];
function skillSortFunction(a, b) {
return (b.skills || []).length - (a.skills || []).length;
}
app.get('candidate/search', function(res,res){
candidate.sort(skillSortFunction);
const mostSkilled = candidate[0];
return res.json(mostSkilled);
})
此处使用原始JavaScript进行演示:
const candidate = [
{"id":1, "name":"Jonh", "skills":["Python","Java","Go","Node","Express"]},
{"id":2, "name":"Mary", "skills":["Go","Python"]},
{"id":3, "name":"Kevin", "skills":["Ruby","Java","Go"]}
];
function skillSortFunction(a, b) {
return (b.skills || []).length - (a.skills || []).length;
}
candidate.sort(skillSortFunction);
const mostSkilled = candidate[0];
console.log("Most skilled candidate:", mostSkilled);
const leastSkilled = candidate[candidate.length-1];
console.log("Least skilled candidate:", leastSkilled );