Reputation: 33
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"
}
}
}
}
}
}
]
}
Below is how I tried
response.resultData[0].fareDetails[Object.keys(response.resultData[0].fareDetails)[0]]
If I try as above I can able to access dynamically up to "xxxxxx20160929" key, but I can't able get how to reach up to "bf" key dynamicaly.
Upvotes: 1
Views: 375
Reputation: 603
If you are able to access up to "xxxxxx20160929" level then create a var to store that level, then use that variable to access the next which you will need to store in a variable, then use both variable to access the key needed.
var1 = response.resultData[0].fareDetails)[0];
var2 = response.resultData[0].fareDetails)[0][var1];
response.resultData[0].fareDetails)[0][var1][var2];
Upvotes: 0
Reputation: 1899
function getBFFromFareDetails(details){
var bfValues = [];
for(var k in details.fareDetails){
// loop over the children of fareDetails
if( details.fareDetails.hasOwnProperty( k ) ) {
//each entry in ;fareDetails'
var itemRoot = details.fareDetails[k]
for(var k1 in itemRoot){
// loop over the children of the first unknown item
if( itemRoot.hasOwnProperty( k1 ) ) {
//return the bf from the first unknown child
return itemRoot[k1].O.AD.bf;
}
}
}
}
}
If you call this with var bf = getBFFromFareDetails(response.resultData[0])
this will return the value for the first bf in the first child of fareDetails
and its first child.
You can see a quick example in action here https://jsfiddle.net/tocsoft/5364x2sp/
Upvotes: 1
Reputation: 1389
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;
Upvotes: 1