I have the following getJSON which was working fine. I decided I wanted to be able to change the data shown on the page based on what the user selected. I have a function that sets a cookie based on the user selection. I want to take the value of this cookie and use it to get a specific value from the JSON object.
The value of the cookie is retrieved and stored in cohort1.
$.getJSON('all_get_login.php?cat_code=stocks&sortvalue=value&sortorder=asc', function(data) {
$.each(data, function(key, val) {
if (val.value == "Yes") {
var cohort1 = readCookie('cohort_id_1');
console.log(cohort1); //gives expected result
var databaseYes = val.cohort1; //THIS LINE IS THE PROBLEM
var databaseNo = 100 - databaseYes;
$("#yes_stocks_db").append(databaseYes + "%");
$("#no_stocks_db").append(databaseNo + "%");
});
});
My JSON object looks like this:
[
{
"cat_code": "stocks",
"group": "fin",
"main_grouping": "Financial",
"highest_level": "Financial",
"category": "Invests in Stocks and Bonds",
"value": "No",
"database_percent": "38.90",
"cohort_1": "43.88",
"cohort_2": "27.66",
"national_percent": "30.16"
},
{
"cat_code": "stocks",
"group": "fin",
"main_grouping": "Financial",
"highest_level": "Financial",
"category": "Invests in Stocks and Bonds",
"value": "Yes",
"database_percent": "61.10",
"cohort_1": "56.37",
"cohort_2": "72.34",
"national_percent": "70.10"
}
]
Here's the problem: in the line in my getJSONthat has this var databaseYes= val.cohort1;, the script is looking for something in the JSON object that matches "cohort1", which will never be in the object. What I need in here is the value of the var cohort1 and not the actual text "cohort1". How can I change this line to accommodate that?
$.eachloop therevar databaseYes = val.database_percent;where "database_percent" is something in the JSON object, it works just fine. The problem is when I try to pass a variable in there instead of something from the actual JSON.var databaseYes = val[cohort1]? Objective is not easy to understand as written. Perhaps an example value of the cookie would help