[英]Getting the highest value excluding a certain value from a nested object property
恐怕我在這里要做的很具體,迭代邏輯超出了我的范圍。 好的...我有一個看起來像這樣的對象:
var answers = { cat1: { q1: { "question": "Why?", "answer": "No", "points": 6 }, q2: { "question": "Why oh why?", "answer": "50%", "points": 15 }, q3: { "question": "Is it true?", "answer": "Maybe", "points": 9 } }, cat2: { q1: { "question": "Hello?", "answer": "Hello", "points": 0 }, q2: { "question": "Why me?", "answer": "Because", "points": 9 }, q3: { "question": "Is it true?", "answer": "Maybe", "points": 0 } }, cat3: { q1: { "question": "why not?", "answer": "I don't know", "points": 15 }, q2: { "question": "What?", "answer": "That", "points": 9 }, q3: { "question": "Is it real?", "answer": "Nope", "points": 6 } } }
對於每個我不知道其屬性名稱的“類別”,我需要找到最高的點, 不包括恰好是15的點(也就是說,15是一種特殊情況,因此我認為9是0中最高的點, 9和15),用於類別中的“ q(n)”嵌套對象。
我想將這些高分中的每一個都加起來,可能是通過+ =“總”變量將它們加在一起。
我覺得好像我應該以某種方式使用underscore.js簡化對象,以便僅剩下q1: 6
等,刪除值為15的屬性,然后使用下划線的_.max()
函數獲得最高分值在將這些高分相加之前,對每個q(n)
進行計算。
在示例中,這將是9加9加9(27)。
感謝您的任何幫助。
您應該使用簡單的for
循環迭代Object
的鍵,然后可以對結果進行總結。
var maxs = {},
tot = 0;
for (var i in answers) {
maxs[i] = 0;
for (var j in answers[i]) {
if (answers[i][j].points != 15) maxs[i] = Math.max(maxs[i], answers[i][j].points);
else delete answers[i][j];
// ^ delete the question if the score is 15
}
tot += maxs[i];
}
結果將是這樣的:
maxs
> {
cat1: 9,
cat2: 9,
cat3: 9
}
tot
> 27
您可以將_.mapObject
與_.mapObject
的自定義iteratee _.max
以按類別獲取最高點:
var maxes = _.mapObject(answers, function (qs) {
var maxq = _.max(qs, function (q) {
return (q.points !== 15) ? q.points : -Infinity;
});
return maxq.points;
});
將輸出
{cat1 = 9,cat2 = 9,cat3 = 9}
http://jsfiddle.net/v80z9w2y/用於演示
_.reduce
將使您得到總數:
var sum = _.reduce(maxes, function(memo, num){ return memo + num; }, 0);
http://jsfiddle.net/v80z9w2y/1/
如果您只對總和感興趣,則可以將這兩個步驟結合起來:
var sum = _.reduce(answers, function (memo, qs) {
var maxq = _.max(qs, function(q) {
return (q.points !== 15) ? q.points : -Infinity;
});
return memo + maxq.points;
}, 0);
這是使用下划線的另一個版本:
var sum = _.reduce(answers, function(memo, cat){
return memo + _.max(_.without( _.pluck(cat, 'points'), 15) );
}, 0);
此代碼可在任何現代瀏覽器中運行,而無需任何庫
var categories = [];
for (var cat in answers) {
categories.push(answers[cat]);
}
var sum = categories.map(function (cat) {
var highest = 0;
for (var q in cat) {
var question = cat[q];
if (question.points !== 15) {
highest = Math.max(highest, question.points);
}
}
return highest;
}).reduce(function (prev, current) {
return prev + current;
}, 0);
答案已經被選擇,但是問題很有趣,所以這是我的嘗試:
function getTotal(answers){
return Object.keys(answers).reduce(function(total, cat){
return total + Math.max.apply(window,
Object.keys(answers[cat]).map(function(question){
return answers[cat][question].points === 15 ? 0 : answers[cat][question].points;
})
);
},0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.