[英]Iterating over a json array whose key value is dynamic
I have a json structure as: 我有一个json结构为:
{
"TestCaseList": [
{
"TC_1": {
"name":"verifyloginpagedetails",
"value":"2"
},
"TC_2": {
"name":"verify registration page details",
"value":"3"
}
}
],
"Summary": {
"v":[
{
"name":"over the ear headphones - white/purple",
"value":1
}
]
}
}
How to extract the values name, value of TC_1 , TC_2 where TC_1 is dynamic ie key of TestCaseList? 如何提取值名称,TC_1,TC_2的值,其中TC_1是动态的,即TestCaseList的键?
You can use the Object.keys
method to get an array of the keys of an object. 您可以使用Object.keys
方法获取对象键的数组。
With a single object in the array at "TestCaseList"
in your JSON object, this will work: 使用JSON对象中"TestCaseList"
数组中的单个对象时,它将起作用:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
If, however, the array at "TestCaseList"
contains more than one one element, you can use this to get each set of keys in an individual array: 但是,如果"TestCaseList"
中的数组包含多个元素,则可以使用此元素获取单个数组中的每组键:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
I'm sure a more elegant solution exists, but this will do the trick. 我敢肯定,存在更优雅的解决方案,但这可以解决问题。
var myObj = {
"TestCaseList":
[{
"TC_1":
{"name":"verifyloginpagedetails",
"value":"2"},
"TC_2":
{"name":"verify registration page details",
"value":"3"}
}],
"Summary":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
}
}
let testCaseListKeys = Object.keys(myObj.TestCaseList[0]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
console.log(tclKey + "\'s name = " + myObj.TestCaseList[0][tclKey].name);
console.log(tclKey + "\'s value = " + myObj.TestCaseList[0][tclKey].value);
}
The console.logs are your output. console.logs是您的输出。 The important values there are the myObj.TestCaseList[0][tclKey].name
and the myObj.TestCaseList[0][tclKey].value
其中的重要值是myObj.TestCaseList[0][tclKey].name
和myObj.TestCaseList[0][tclKey].value
** UPDATE ** ** 更新 **
After answering the question Ananya asked how to do this same thing if the object had a different structure. 回答问题后,Ananya问如果对象具有不同的结构,该如何做同样的事情。
Updated Object: 更新的对象:
var myObj2 = {
"TestCaseList":
[{
"TC_1":{
"name":"verifyloginpagedetails",
"value":"2"}
},
{
"TC_2":{
"name":"verify registration page details",
"value":"3" }
}],
"Summary":
{
"v":[ {"name":"over the ear headphones - white/purple","value":1} ]
}
}
Updated JavaScript: 更新的JavaScript:
for(x=0;x<myObj2.TestCaseList.length;x++) {
let testCaseListKeys = Object.keys(myObj2.TestCaseList[x]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
//console.log(tclKey);
console.log(tclKey + "\'s name = " + myObj2.TestCaseList[x][tclKey].name);
console.log(tclKey + "\'s value = " + myObj2.TestCaseList[x][tclKey].value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.