嵌套的for循环可从嵌套数组创建节/ div

时间:2018-11-14 01:30:48

标签: javascript arrays json for-loop

我需要在网站上显示一些嵌套的Json数组。本质上,我正在导出hyper V主机及其虚拟机,并希望以html显示它们。

我从json中获取了数据,并在脚本标签的html索引中将其放入了var中。 (原因是为了避免需要Web服务器,长话短说有工作限制)

我在弄清楚如何读取数组项和嵌套循环以在各节中显示Hyper V,然后在每个节中将它们的vm列为div时遇到麻烦。

这是我导入的json数据的简化版本(在我的html中,它是一个长字符串,在此处隔开以方便阅读。

<script type="text/javascript">
var sample =
[
    {
        "host1.domain.com.au":[
            {
                "SERVER1":{
                    "Replication Status":"Nil",
                    "VM Name":"SERVER1",
                    "RAM":8,
                    "CPUs":4,
                    "Hard Drives":128849018880,
                    "IP Address":null
                },
                "SERVER2":{
                    "Replication Status":"Primary",
                    "VM Name":"SERVER2",
                    "RAM":8,
                    "CPUs":4,
                    "Hard Drives":128849018880,
                    "IP Address":null
                }
            }
        ]
    },
    {
        "host2.domain.com.au":[
            {
                "SERVER3":{
                    "Replication Status":"Primary",
                    "VM Name":"SERVER3",
                    "RAM":8,
                    "CPUs":4,
                    "Hard Drives":107374182400,
                    "IP Address":"10.69.185.113"
                },
                "SERVER4":{
                    "Replication Status":"Primary",
                    "VM Name":"SERVER4",
                    "RAM":8,
                    "CPUs":2,
                    "Hard Drives":64424509440,
                    "IP Address":"10.69.185.25"
                }
            }
        ]
    }
];
</script>

我想要的样品是:

    <section class="hyperv-host">    
        <h1>host1.domain.com.au</h1>
        <div class="vm">
            <h2>SERVER1</h2>
        <div class="vm">
            <h2>SERVER2</h2>
    </section>
    <section class="hyperv-host">    
        <h1>host2.domain.com.au</h1>
        <div class="vm">
            <h2>SERVER3</h2>
        <div class="vm">
            <h2>SERVER4</h2>
    </section>

我可以将主机划分为多个部分,但其中涉及创建了一个新数组,该数组随后没有其余数据,因此无法在其中嵌套循环。如此迷失。

2 个答案:

答案 0 :(得分:1)

这是一个非常简单的示例,说明如何进行锻炼。抱歉,嵌套的for循环很容易理解。

$(function () {

    // Listen to the click event of any buttons with a `calculate` attribute
    $("button[calculate]").click(function (e) {

        var $this=$(this);

        //Read the value from hml5 attribute
        var value=$this.data("salario");

        var mTotal="Total : "+ value;
        // you can add if your IF condition here to update mTotal 

        // First get the outer TD,
        // Then get the p tag with result attribute
        // Then update the text with your mTotal variable value
        $this.closest("td").find("p[result]").text(mTotal);

    });
});

答案 1 :(得分:0)

您可以执行以下操作:

var sample =  [
  {
    "host1.domain.com.au":[
      {
        "SERVER1":{
          "Replication Status":"Nil",
          "VM Name":"SERVER1",
          "RAM":  8,
          "CPUs": 4,
          "Hard Drives":128849018880,
          "IP Address":null
        }
      }
    ],
    "host2.domain.com.au": [
      {
        "SERVER3": {
          "Replication Status":  "Primary",
          "VM Name": "SERVER3",
          "RAM":8,
          "CPUs":4,
          "Hard Drives":  107374182400,
          "IP Address":"10.69.185.113"
        },
        "SERVER4": {
          "Replication Status":"Primary",
          "VM Name":"SERVER4",
          "RAM":8,
          "CPUs":2,
          "Hard Drives":64424509440,
          "IP Address":  "10.69.185.25"
        }
      }
    ]
  }
];

//This gets each host as a key
const sampleHosts = Object.keys(sample[0]);

//Iterate through every key of the sample
sampleHosts.forEach(function (host) {
  //Create a new section element and give it the right class
  let hostSection = document.createElement("section");
  hostSection.classList.add("hyperv-host");

  //Create a new h1 element and set it's text content to the current host
  let hostHeader = document.createElement("h1");
  hostHeader.textContent = host;

  //Append the header to the newly created section
  hostSection.append(hostHeader);

  //We now grab the servers from the host
  const serverArray = sample[0][host][0];

  //get the rows ready based on the current servers
  const serverRows = makeServersRows(serverArray);

  //From the array we got on the function above, we can iterate through
  serverRows.forEach(function(serverRow) {
    //We just append the rows to the section we created above
     hostSection.append(serverRow);
  });

  //Finally we append the host filled with the server rows to the main body
  document.body.append(hostSection);
});

function makeServersRows(servers) {
  //Servers is an object, so we need to get it's keys again to iterate through it
  const serverKeys = Object.keys(servers);
  //We user map instead of forEach because we want to make a new array based on the values of the servers
  const serverRows = serverKeys.map(function(server) {
    //Create a new div
    let serverDiv = document.createElement("div");
    serverDiv.classList.add("vm");

    //Create a new header
    let serverHeader = document.createElement("h2");
    serverHeader.textContent = server;

    //Put them together
    serverDiv.append(serverHeader);

    //Return each div indiviually to an array outside the .map function
    return serverDiv;
  });

  //Once we have iterated through every server, we return the HTML we created as an array
  return serverRows;
}

对此有一些想法:

  • 我会尝试看看是否可以重新格式化示例对象的结构方式,现在您有一个数组,该数组包含1,只有一个对象,每个主机内部都具有键,为什么不这样做像这样:

    sample = {"host1.domain": {...}, "host2.domain": {...}}

  • 与每台主机内的服务器相同

我还建议您研究Object.keysmapforEach,以了解此答案背后的原因!