简体   繁体   中英

How to use a variable as an index to get a specific value out of a JSON array in Javascript?

I simply want to pinpoint a specific value out of a JSON array.

Sample of JSON array:

{
    "00002": {
        "Job Number": "00002",
        "Company": "Corporate",
        "Supervisor": "Great Person",
        "Date Input": "2016-01-07"
    },

    "00003": {
        "Job Number": "00003",
        "Company": "SmallGuy",
        "Supervisor": "Awful Person",
        "Date Input": "2012-03-05"
    }
}

This works in Javascript:

alert(javascript_array["00002"].Company);

But I want use a dynamic variable to call a record, like this:

var my_variable = 00002;

//OR I've tried:

var my_variable = "'"+00002+"'";

alert(javascript_array[my_variable].Company); //DOES NOT WORK. UNDEFINED??

No matter what I do, I can't use a variable mid-array call.

Help please!

Use the string as key.

var my_variable = '00002';

 var object = { "00002": { "Job Number": "00002", "Company": "Corporate", "Supervisor": "Great Person", "Date Input": "2016-01-07" }, "00003": { "Job Number": "00003", "Company": "SmallGuy", "Supervisor": "Awful Person", "Date Input": "2012-03-05" } } my_variable = '00002'; document.write(object[my_variable].Company); 

For getting all keys from the object, you can use Object.keys() :

 var object = { "00002": { "Job Number": "00002", "Company": "Corporate", "Supervisor": "Great Person", "Date Input": "2016-01-07" }, "00003": { "Job Number": "00003", "Company": "SmallGuy", "Supervisor": "Awful Person", "Date Input": "2012-03-05" } }, keys = Object.keys(object); keys.forEach(function (k) { document.write(object[k].Company + '<br>'); }); 

Your key is a string, but your variable isn't, so there's no match. Just use this:

var my_variable = "00002";

To access key items for a JSON object you need to use strings, but if not it will attempt to convert the value into a string using .toString() . For your first case you are attempting to define a number:

var my_variable = 00002;

Although 00002 isn't a valid value for a number, as such it will contain the value 2 , and converted to a string it's "2" . In your JSON there is no such javascript_array["2"] . The second case has a similar problem:

"'"+00002+"'" => "'"+2+"'" => "'2'"

Also there is not such javascript_array["'2'"] , along with this you are adding unneeded quotes '...' . In this case ( as others pointed out ) just define my_variable as a string with the value "00002" .

var my_variable = "00002";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM