Rookie
Rookie

Reputation: 5467

JQuery: read value from json

I have the following code:

var Configuration = {
    conf : {},
    buildConfig : function (){
    var configugration = {};

    configugration.supportedCountsInJSON = ["closedSRCount","resSRCount","openTAGCount","SECount"];
    return configugration;  
},

and a variable like this:

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

When i try to read the values from the above Json based on the keys from the Configuration var as follws, i get 'undefined':

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]);
            }

        });

I know that the

sKey = Configuration.conf.supportedCountsInJSON[id]

variable is giving me the following keys when i log them out:

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

But, when i try to read the value for each key in the Json (eg, associateId) in the above code as follows, I get 'undefined' & am unable to read those:

teamCountsJson[index].sKey

Any thoughts?

Please advise,

Thanks!

Upvotes: 0

Views: 53

Answers (2)

Mario
Mario

Reputation: 2942

To access a variably-named property on a javscript object, you need to use the [] syntax.

In your code, you define the value you want in sKey, then try to access it like this:

teamCountsJson[index].sKey

That's grabbing the sKey property of the teamCountsJson[index] object, which will be undefined.

You probably meant to do this:

teamCountsJson[index][sKey]

Upvotes: 1

adeneo
adeneo

Reputation: 318162

There is no sKey property, if you want to use a variable containing a property name, you have to use bracket notation

teamCountsJson[index][sKey]

Upvotes: 1

Related Questions