javascript - forEach 方法似乎跳过一个条目

标签 javascript node.js arrays object

目标

我正在尝试创建一个函数,它接受“投票”数组并返回一个对象,其中包含每个“候选人”获得 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/

相关文章:

javascript - 如何合并对象数组中的重复项并对特定属性求和?

javascript - 如何在 Three.js 中使用 RayCaster 拾取文本网格?

javascript - 使用 Content-Range 在 Node.js 中流式传输音频

python - 是否可以通过 Python 中的另一个字符串列表过滤子字符串列表?

javascript - 不能包含 javascript(401 错误)

javascript - jQuery .offset() 在每个浏览器中根本无法正常工作

node.js - 这在 NodeJS 中是未定义的

javascript - Boilerplate Github存储库将无法运行npm install,ERR!在 '…compile-2.0.0-beta.4.t'附近进行解析时,JSON输入意外结束

c++一次检查所有数组值

编译器返回错误 "char *(int)' 与 'int ()' 的间接级别不同“即使返回的数据似乎与函数返回类型匹配