使用变量从JSON对象获取值

时间:2022-09-23 14:00:31

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.

我有以下getJSON工作正常。我决定我希望能够根据用户选择的内容更改页面上显示的数据。我有一个功能,根据用户选择设置cookie。我想获取此cookie的值并使用它从JSON对象获取特定值。

The value of the cookie is retrieved and stored in cohort1.

检索cookie的值并将其存储在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:

我的JSON对象如下所示:

[
    {
        "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?

这是问题所在:在我的getJSONt行中有这个var databaseYes = val.cohort1;,脚本在JSON对象中寻找匹配“cohort1”的东西,它永远不会出现在对象中。我在这里需要的是var cohort1的值而不是实际的文本“cohort1”。如何更改此行以适应这种情况?

1 个解决方案

#1


2  

You can use [] object notation to pass a variable as a property name.

您可以使用[]对象表示法将变量作为属性名称传递。

var cohort1 ='foo';
var databaseYes = val[cohort1];

This is the equivalent of val.foo

这相当于val.foo

#1


2  

You can use [] object notation to pass a variable as a property name.

您可以使用[]对象表示法将变量作为属性名称传递。

var cohort1 ='foo';
var databaseYes = val[cohort1];

This is the equivalent of val.foo

这相当于val.foo