簡體   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