繁体   English   中英

遍历键值为动态的json数组

[英]Iterating over a json array whose key value is dynamic

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM