如何让常量变量在 JavaScript 代码中动态工作

how to have a constant variable work dynamically in JavaScript code

谁能帮我解决 javascript 这里的问题? 我需要知道如何使此代码中的 "Year" 动态化。

var dataAdapter = new $.jqx.dataAdapter(source, { 
    async: false, 
    autoBind: true,

    beforeLoadComplete: function (records) {
        newRecords = new Array(
            { Year: 2012, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }, 
            { Year: 2013, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }, 
            { Year: 2014, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }
        );

        for (var i = 0; i < records.length; i++) {
            var currentRecord = records[i];

            switch (currentRecord.Year) {
                case "2012":
                    newRecords[0]["Site" + currentRecord.SiteId] =       
                        parseFloat(currentRecord.Count);
                    break;

                case "2013":
                    newRecords[1]["Site" + currentRecord.SiteId] = 
                        parseFloat(currentRecord.Count);
                    break;

                case "2014":
                    newRecords[2]["Site" + currentRecord.SiteId] = 
                        parseFloat(currentRecord.Count);
                    break;
            }
        }

        return newRecords;
    },

    loadError: function (xhr, status, error) {
        alert('Error loading "' + source.url + '" : ' + error);
    }
});

非常感谢任何帮助! 基本上我有 json 数据以这种格式出现:

{"Year":"2012","SiteId":"In Process","Count":6},{"Year":"2012","SiteId":"Resolved","Count":3},{"Year":"2013","SiteId":"In process","Count":4},{"Year":"2013","SiteId":"Resolved","Count":3},{"Year":"2013","SiteId":"Under Observati","Count":1},{"Year":"2014","SiteId":"In Process","Count":7},{"Year":"2014","SiteId":"Resolved","Count":39},{"Year":"2014","SiteId":"Under Observati","Count":1}

因为我正在查询数据库中的这些数据,所以我不确定我会得到多少条记录。但我知道每年最多有 4 个 SiteId(处理中、已解决、观察中、临时修复)。我需要根据每年绑定数据。喜欢

{Year:2012,In Process:6,Resolved:3}, 
{year:2013, In Process:4,Resolved:3, Under Observation:1}

如果你可以使用外部库,我建议 Lodash。 您可以使用 indexBy 函数以这种方式正确转换 newRecords 数组:

_.indexBy(newRecords, 'Year');

如果 newRecords(根据您的问题)是:

[
    { Year: 2012, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }, 
    { Year: 2013, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }, 
    { Year: 2014, Site1: 0, Site2: 0, Site3: 0, Site4: 0 }
]

_.indexBy(newRecords, 'Year'); returns:

{ 
    '2012': { Year: 2012, Site1: 0, Site2: 0, Site3: 0, Site4: 0 },
    '2013': { Year: 2013, Site1: 0, Site2: 0, Site3: 0, Site4: 0 },
    '2014': { Year: 2014, Site1: 0, Site2: 0, Site3: 0, Site4: 0 } 
}

然后您可以遍历任何新 "year-field-based" sub-objects 来计算 sub-objects.

中的任何参数

希望对您有所帮助。