循环访问键值为动态的 json 数组



我有一个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
}
]
}
}

如何提取值名称,TC_1的值,TC_2 TC_1动态的位置,即TestCaseList的键?

可以使用Object.keys方法获取对象的键数组。

如果数组中的单个对象位于 JSON 对象的"TestCaseList",这将起作用:

// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);

但是,如果"TestCaseList"处的数组包含多个元素,则可以使用它来获取单个数组中的每组键:

testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));

我确信存在更优雅的解决方案,但这可以解决问题。

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);
}

console.logs 是您的输出。那里的重要值是myObj.TestCaseList[0][tclKey].namemyObj.TestCaseList[0][tclKey].value

**

更新**

在回答了这个问题之后,Ananya问如果物体有不同的结构,该怎么做同样的事情。

更新的对象:

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}  ]
}
}

更新的 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);
}
}

最新更新