[英]Access JSON key value dynamically using jquery
Below is my json which is dynamic. 下面是我的动态JSON。 I want to access 'bf' key in the json , 'xxxxxx20160929' and 'yyy813AI20160929' keys are dynamic but json structure will be the same
我想访问json中的'bf'键,'xxxxxx20160929'和'yyy813AI20160929'键是动态的,但json结构将相同
{
"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. 如果我按上述方式尝试,则可以动态访问高达“ xxxxxx20160929”的密钥,但是无法动态地获取高达“ bf”的密钥。
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;
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. 如果使用
var bf = getBFFromFareDetails(response.resultData[0])
调用,则将返回fareDetails
的第一个子代及其第一个子代中的第一个bf的值。
You can see a quick example in action here https://jsfiddle.net/tocsoft/5364x2sp/ 您可以在这里看到一个运行中的快速示例https://jsfiddle.net/tocsoft/5364x2sp/
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. 如果您能够访问“ xxxxxx20160929”级别,则创建一个变量来存储该级别,然后使用该变量访问您需要存储在变量中的下一个变量,然后使用这两个变量来访问所需的密钥。
var1 = response.resultData[0].fareDetails)[0];
var2 = response.resultData[0].fareDetails)[0][var1];
response.resultData[0].fareDetails)[0][var1][var2];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.