JQuery:从json读取值

时间:2015-03-06 23:20:16

标签: javascript jquery json

我有以下代码:

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",
}]

当我尝试根据配置变量中的键从上面的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

有什么想法吗?

请指教,

谢谢!

2 个答案:

答案 0 :(得分:1)

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

teamCountsJson[index][sKey]

答案 1 :(得分:1)

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

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

teamCountsJson[index].sKey

抓取teamCountsJson[index]对象的sKey属性,该属性为undefined

您可能打算这样做:

teamCountsJson[index][sKey]