我在解决这种情况时遇到麻烦,我需要根据另一个数组的键值过滤一个数组。这可能很容易,但是我无法捕获正确的键值对。
我有这一系列标记:
marks = {
eng : 90,
maths : 50,
phy : 60,
chem : 75,
bio : 85,
}
另一个具有相同键名的标记数组:
tags = {
eng : 'English',
maths : 'Maths',
phy : 'Physics',
chem : 'Chemistry',
bio : 'Biology',
}
现在,tags
如果标记>65
在marks
数组中并且期望的结果是:
filteredTags = {
eng : 'English',
chem : 'Chemistry',
bio : 'Biology',
}
甚至更好:
filteredTags = ['English', 'Chemistry', 'Biology']
到目前为止我尝试过的是:
filteredTags = []
$.each(marks, function(ind, val) {
if (val > 60){
filteredTags = tags.filter(function(i,v) {
return (i == ind)
}
})
使用数组会更容易,但是这段代码应该可以工作:
let marks = {
eng : 90,
maths : 50,
phy : 60,
chem : 75,
bio : 85,
}
let tags = {
eng : 'English',
maths : 'Maths',
phy : 'Physics',
chem : 'Chemistry',
bio : 'Biology',
}
function getTagsWithMarksAbove(num) {
let result = [];
for(prop in marks) { // Iterate over the properties of the marks object
if(marks[prop] > num) // Check if mark is above the specified number
result.push(tags[prop]); // Add value of tags property with the same name to result array
}
return result;
}
console.log(getTagsWithMarksAbove(65))