目标
我正在尝试创建一个函数,它接受“投票”数组并返回一个对象,其中包含每个“候选人”获得 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 input_data = raw_data;
复制对象数组是有问题的,因为复制数组不会自动创建对象的新副本。它只是一个包含对原始对象的引用的新数组,因此如果您更改新数组中的对象,您也会更改原始对象。
所以你需要制作new copies of the objects也是:
const input_data = raw_data.map(obj => ({...obj}));
您可以使用 reduce
稍微简单地解决您的问题.
const data = [{"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}];
// We initialise the `reduce` with a new `{}` object,
// which is updated with each iteration.
// `acc` is the accumulator, `c` is the current element
const result = data.reduce((acc, c) => {
// For each object in the array we grab the key and value
Object.entries(c).forEach(([ key, value ]) => {
// If our initial object doesn't already have a key
// that matches, create one and set it to zero
acc[key] = acc[key] || 0;
// And if the value is one, increase the value of that property
if (value === 1) acc[key]++;
});
// Make sure to return the initial object
// for the next iteration
return acc;
}, {});
console.log(result);
关于javascript - forEach 方法似乎跳过一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67875567/