我的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的键?
答案 0 :(得分:0)
您可以使用Object.keys
方法来获取对象键的数组。
在JSON对象中"TestCaseList"
处的数组中有一个对象,这将起作用:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
但是,如果"TestCaseList"
处的数组包含一个以上的元素,则可以使用它来获取单个数组中的每组键:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
答案 1 :(得分:0)
我确定存在一个更优雅的解决方案,但这可以解决问题。
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].name
和myObj.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);
}
}