javascript数组 - 在给定键处增加值

标签 javascript jquery arrays

我有一个动态数组,如果数组中存在该键,我将尝试将该值递增 1。根据我的调试,它正在递增键并创建第二个键/值对。

我的代码片段:

        for (var i = 0; i < choices.length; i++) {
            console.log(choices[i]);
            if (choices[i].YearTermId == 1) {
                if (!lookup(firstChoice, choices[i].FirstChoiceOptionId)) {
                    firstChoice.push({
                        key: choices[i].FirstChoiceOptionId,
                        value: 1
                    });
                } else {
                    firstChoice[choices[i].FirstChoiceOptionId] = firstChoice[choices[i].FirstChoiceOptionId] + 1;
                }

更多如果/否则..

    function lookup( arr, name ) {
        for(var i = 0, len = arr.length; i < len; i++) {
            if( arr[ i ].key === name )
                return true;
        }
        return false;
    }

最佳答案

您在本应使用对象的地方使用了数组。如果您使用一个对象,您的代码可以重写为:

var firstChoice = {};

for (var i = 0; i < choices.length; i++) {
    var firstChoiceOptionId = choices[i].FirstChoiceOptionId;

    if (choices[i].YearTermId == 1) {
        firstChoice[firstChoiceOptionId] = firstChoice[firstChoiceOptionId]
                ? firstChoice[firstChoiceOptionId] + 1
                : 1;

        /* ... */
    }
}

如果之后需要将数据作为数组,只需将其映射即可:

var firstChoiceArray = Object.keys(firstChoice).map(function(key) {
    return {
        key: key,
        value: firstChoice[key]
    };
});

相反,如果您有一个输入数组并想将其转换为对象进行操作,则将其归约:

var firstChoice = firstChoiceArray.reduce(function(result, current) {
    result[current.key] = current.value;

    return result;
}, {});

关于javascript数组 - 在给定键处增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212994/

相关文章:

asp.net - 具有动态内容的 JQuery

javascript - 滚动时执行动画

javascript - ES6 数组扩展极端怪异。它仅使用 webpack 恢复为常规数组

c++ - 尝试创建指针数组时不允许使用不完整的类型

C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组?

Javascript 的 super 构造函数 - 澄清吗?

javascript - 使用 jquery 简单验证按钮单击操作

javascript - 如何调用其他文件中的RequireJS函数?如何分离RequireJS文件?

php - 使用 js/ajax 将参数传递给 php 文档

jQuery $.post() 和 PHP if(isset($_POST)) 帮助优化