【发布时间】:2021-06-08 01:32:19
【问题描述】:
目标
我正在尝试创建一个函数,该函数将采用“投票”数组并返回一个对象,该对象包含每个“候选人”获得 1 分的次数。
例如一个数组,如:
[
{
"blue": 1,
"red": 3,
"purple": 2,
"yellow": 4
},
{
"blue": 2,
"red": 3,
"purple": 4,
"yellow": 1
},
{
"blue": 1,
"red": 2,
"purple": 4,
"yellow": 3
},
{
"blue": 3,
"red": 4,
"purple": 2,
"yellow": 1
}
];
应该返回一个对象
{
"blue": 2,
"red": 0,
"purple": 0,
"yellow": 2
}
当前代码
目前我已经写好了函数
// adds up the first choice results from raw data
// return object containing number of first choice votes each candidate received
const add_first_choices = function (raw_data) {
// create object to store number of first choices
const storage_obj = empty_candidate_obj(raw_data);
// loop through results, adding first choices to storage_obj
raw_data.forEach(function (single_voter_obj) {
Object.values(single_voter_obj).forEach(function (value) {
if (value === 1) {
storage_obj[getKeyByValue(single_voter_obj, value)] += 1;
}
});
});
return storage_obj;
};
它使用以下两个其他函数
// returns object of candidate names, each with value of 0
const empty_candidate_obj = function (raw_data) {
const input_data = raw_data;
let first_vote = input_data[0];
const keys = Object.keys(first_vote);
keys.forEach(function (key) {
first_vote[key] = 0;
});
return first_vote;
};
和
// returns key from object value
const getKeyByValue = function (object, value) {
return Object.keys(object).find((key) => object[key] === value);
};
问题
当将上面的数组输入到我的函数中时,它会返回
{
blue: 1,
red: 0,
purple: 0,
yellow: 2
}
=> 不如预期!
你知道我做错了什么吗?
感谢任何回复:)
【问题讨论】:
-
const output = {}; for (const o of raw_data) { for (const key in o) { output[key] ||= 0; if (o[key] === 1) output[key]++ } } -
在这种情况下,调试技巧就派上用场了。查看this article 了解一些提示,开始吧。
标签: javascript node.js arrays object