How do I loop through deeply nested properties of a JavaScript object?

后端 未结 1 1106
攒了一身酷
攒了一身酷 2020-12-14 09:22

I have a JavaScript object with 3 levels of nesting. I am having a hard time getting the values from the 3rd level of nesting.

I have done some research on SO and ge

相关标签:
1条回答
  • 2020-12-14 10:06

    You have an object (customers) with an array stored at cluster, which you can iterate through with

    var i, cluster;
    for (i = 0; i < customers.cluster.length; i++)
    {
      cluster = customers.cluster[i];
    }
    

    cluster has an array stored at segment which you can iterate through with:

    var j, segment;
    for (j = 0; j < cluster.segment.length; j++)
    {
      segment = cluster.segment[j];
    }
    

    segment has an array stored at node which you can iterate through with:

    var k, node;
    for (k = 0; k < segment.node.length; k++)
    {
      node = segment.node[k];
    }
    

    You can combine all of these to iterate through every node of every segment of every cluster on customers just by combining these loops:

    var i, cluster, j, segment, k, node;
    for (i = 0; i < customers.cluster.length; i++)
    {
      cluster = customers.cluster[i];
    
      for (j = 0; j < cluster.segment.length; j++)
      {
        segment = cluster.segment[j];
    
        for (k = 0; k < segment.node.length; k++)
        {
          node = segment.node[k];
          //access node.xpos, node.ypos here
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题