我在JavaScript中有以下scores
对象:
[
{
"id":37,
"title":"Over achieving",
"description":"Exceeding expectations",
"threshold":10,
},
{
"id":36,
"title":"Achieving",
"description":"Achieving expectations",
"threshold":6,
},
{
"id":35,
"title":"Under achieving",
"description":"Not achieving expectations",
"threshold":3,
}
]
我正在尝试找出如何创建一种方法,该方法将根据分数阈值确定的值返回分数对象。
我尝试了以下操作,但只有在值等于分数阈值时才返回分数,而不是在分数阈值之间。
scores.find(o => o.threshold <= progress && o.threshold >= progress)
所以场景是,一个人的value
进度为5,我希望该方法返回id
为35的分数数组项,因为5在3到6之间。同样,如果进度value
为7,那么我希望该方法返回id
为36的分数数组项,因为7在6到10之间。
我确定我离你不远。
答案 0 :(得分:1)
您似乎正在寻找阈值低于或等于进度的数组中的第一项。表达式
scores.find(o => o.threshold <= progress)
会这样做。
答案 1 :(得分:0)
如果您首先以相反的顺序对scores
数组进行排序,则可以调整回调以找到threshold
仅比progress
小的第一个分数。
// doing it this way solely to keep it on a single line.
const scores = JSON.parse('[{"id":37,"title":"Over achieving","description":"Exceeding expectations","threshold":10},{"id":36,"title":"Achieving","description":"Achieving expectations","threshold":6},{"id":35,"title":"Under achieving","description":"Not achieving expectations","threshold":3}]');
const getScore = (progress) => scores.sort((a, b) => b.threshold - a.threshold).find(score => score.threshold <= progress);
const showScore = (progress) => {
const lowestThreshold = scores.sort((a, b) => a.threshold - b.threshold)[0];
const score = getScore(progress) || lowestThreshold;
console.log(`${progress} returns`, score.id);
};
const allValues = [...Array(15).keys()].map(showScore);
答案 2 :(得分:0)
即使您的scores
数组否按阈值排序。
let progress = 5;
let scores = [{"id":37, "title":"Over achieving", "description":"Exceeding expectations", "threshold":10,}, {"id":36, "title":"Achieving", "description":"Achieving expectations", "threshold":6,}, {"id":35, "title":"Under achieving", "description":"Not achieving expectations", "threshold":3,}]
let item = scores.filter(o => (o.threshold <= progress)).reduce((acc, curr) => (curr.threshold >= acc.threshold)? curr: acc)
console.log(item);
console.log(item.id);
我希望这会有所帮助;)