siva shanker siva shanker - 2 months ago 7
Javascript Question

Access json key value dynamically using jquery


  1. Below is my json which is dynamic. I want to access 'bf' key in the json , 'xxxxxx20160929' and 'yyy813AI20160929' keys are dynamic but json structure will be the same






{
"resultData": [
{
"a": "124",
"b": "0",
"c": "0",
"flc_schedu": {
"e": "6",
"f": "en",
"xxxxxx20160929": [
{"ID": "yyyyyyyy" },
{"ID": "fffff"}
]
},
"fareDetails": {
"xxxxxx20160929": {
"yyy813AI20160929": {
"O": {
"AD": {
"bf": "2527"
}
}
}
}
}
}
]
}



  1. Below is how i tried






response.resultData[0].fareDetails[Object.keys(response.resultData[0].fareDetails)[0]]



  1. If i try as above i can able to access dynamically up to "xxxxxx20160929" key, but i cannt able get how to reach up to "bf" key dynamicaly.



Please help me out with fiddle link

Answer

You can reference an object using the array syntax.

var one = 'xxxxxx20160929';
var two = 'yyy813AI20160929';
data.resultData[0].fareDetails[one][two].O.AD.bf;

UPDATE:

This code assumes there is only one dynamic object at each layer.

var one = Object.keys(data.resultData[0].fareDetails)[0];
var two = Object.keys(data.resultData[0].fareDetails[one])[0];
var thing = data.resultData[0].fareDetails[one][two].O.AD.bf;
Comments