JQuery:从 JSON 读取值

JQuery: read value from json

本文关键字:读取 JSON JQuery      更新时间:2023-09-26

我有以下代码:

var Configuration = {
    conf : {},
    buildConfig : function (){
    var configugration = {};
    configugration.supportedCountsInJSON = ["closedSRCount","resSRCount","openTAGCount","SECount"];
    return configugration;  
},

还有一个像这样的变量:

var teamCountsJson = 
[   {
    "associateId" : "AA029693",
    "closedSRCount" : "10",
    "resSRCount" : "8",
    "openTAGCount" : "0",
    "SECount" : "7",
},
{
    "associateId" : "BB029693",
    "closedSRCount" : "4",
    "resSRCount" : "1",
    "openTAGCount" : "0",
    "SECount" : "1",
}]

当我尝试根据配置变量中的键作为 follws 从上述 Json 中读取值时,我得到"未定义":

calculateMinCounts: function(teamCountsJson){
    $.each(teamCountsJson, function(index){
        var minValues = [];
        var sKey ='';
        $.each(Configuration.conf.supportedCountsInJSON, function(id){
            minValues = [];
            sKey = Configuration.conf.supportedCountsInJSON[id]
            if(teamCountsJson[index].hasOwnProperty(sKey)){
                minValues.push(teamCountsJson[index].sKey);
                console.log('sKey='+sKey+', minValues='+JSON.stringify(teamCountsJson[index].sKey)); //Unable to read the value 'undefined'
            }
            else{
                //console.log('associateId does not exit!!'+Configuration.conf.supportedCountsInJSON[id]);
            }
        });

我知道

sKey = Configuration.conf.supportedCountsInJSON[id]

当我注销它们时,变量给了我以下键:

["closedSRCount","resSRCount","openTAGCount","SECount"];

但是,当我尝试在上面的代码中读取 Json(例如,associateId)中每个键的值时,如下所示,我得到"未定义"并且无法读取这些值:

teamCountsJson[index].sKey

有什么想法吗?

请指教,

谢谢!

没有sKey属性,如果要使用包含属性名称的变量,则必须使用括号表示法

teamCountsJson[index][sKey]

若要访问 javscript 对象上的可变名称属性,需要使用[]语法。

在代码中,定义所需的值 sKey ,然后尝试像这样访问它:

teamCountsJson[index].sKey

这是抓取teamCountsJson[index]对象的 sKey 属性,该属性将undefined .

您可能打算这样做:

teamCountsJson[index][sKey]