0

I have a JavaScript object when tried to iterate through it, it throwing zero as the length of the object and even undefined when accessed any key inside the object.

init();

function init() {
  if (window.goSamples) goSamples(); // init for these samples -- you don't need to call this
  var $ = go.GraphObject.make; // for conciseness in defining templates in this function

  myDiagram =
    $(go.Diagram, "myDiagramDiv", // must be the ID or reference to div
      {
        initialContentAlignment: go.Spot.Center
      });

  // define all of the gradient brushes
  var graygrad = $(go.Brush, "Linear", {
    0: "#F5F5F5",
    1: "#F1F1F1"
  });
  var bluegrad = $(go.Brush, "Linear", {
    0: "#CDDAF0",
    1: "#91ADDD"
  });
  var yellowgrad = $(go.Brush, "Linear", {
    0: "#FEC901",
    1: "#FEA200"
  });
  var lavgrad = $(go.Brush, "Linear", {
    0: "#EF9EFA",
    1: "#A570AD"
  });

  // define the Node template for non-terminal nodes
  myDiagram.nodeTemplate =
    $(go.Node, "Auto", {
        isShadowed: true
      },
      // define the node's outer shape
      $(go.Shape, "RoundedRectangle", {
          fill: graygrad,
          stroke: "#D8D8D8"
        },
        new go.Binding("fill", "color")),
      // define the node's text
      $(go.TextBlock, {
          margin: 8,
          font: "bold 11px Helvetica, bold Arial, sans-serif"
        },
        new go.Binding("text", "key")),
      $("TreeExpanderButton", {
        margin: new go.Margin(30, 5, 5, 5)
      })
    );

  // define the Link template
  myDiagram.linkTemplate =
    $(go.Link, // the whole link panel
      {
        selectable: false
      },
      $(go.Shape)); // the link shape

  // create the model for the double tree
  myDiagram.model = new go.TreeModel([
    // these node data are indented but not nested according to the depth in the tree

    {
      key: "D",
      color: lavgrad
    },
    {
      key: "Z",
      parent: "C",
      dir: "left",
      color: bluegrad
    },
    {
      key: "C",
      parent: "D",
      dir: "left",
      color: bluegrad
    },
    {
      key: "B",
      parent: "D",
      dir: "left",
      color: bluegrad
    },
    {
      key: "I",
      parent: "H",
      dir: "right",
      color: bluegrad
    },
    {
      key: "K",
      parent: "H",
      dir: "left",
      color: bluegrad
    },
    {
      key: "K",
      parent: "E",
      dir: "left",
      color: bluegrad
    },
    {
      key: "J",
      parent: "E",
      dir: "right",
      color: bluegrad
    },
    {
      key: "H",
      parent: "D",
      dir: "right",
      color: bluegrad
    },
    {
      key: "E",
      parent: "D",
      dir: "right",
      color: bluegrad
    },

  ]);

  doubleTreeLayout(myDiagram);
}

function doubleTreeLayout(diagram) {
  // Within this function override the definition of '$' from jQuery:
  var $ = go.GraphObject.make; // for conciseness in defining templates
  diagram.startTransaction("Double Tree Layout");

  // split the nodes and links into two Sets, depending on direction
  var leftParts = new go.Set(go.Part);
  var rightParts = new go.Set(go.Part);

  var LP = leftParts;
  var items = LP.ud;

  document.getElementById("objInfo").innerHTML = "<br> Items Length : " + items.length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys Length : " + Object.keys(items).length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys: " + items;


  separatePartsByLayout(diagram, leftParts, rightParts);
  // but the ROOT node will be in both collections

  // create and perform two TreeLayouts, one in each direction,
  // without moving the ROOT node, on the different subsets of nodes and links
  var layout1 =
    $(go.TreeLayout, {
      angle: 180,
      arrangement: go.TreeLayout.ArrangementFixedRoots,
      setsPortSpot: false
    });

  var layout2 =
    $(go.TreeLayout, {
      angle: 0,
      arrangement: go.TreeLayout.ArrangementFixedRoots,
      setsPortSpot: false
    });

  layout1.doLayout(leftParts);
  layout2.doLayout(rightParts);

  diagram.commitTransaction("Double Tree Layout");
}

function separatePartsByLayout(diagram, leftParts, rightParts) {
  var root = diagram.findNodeForKey("D");
  if (root === null) return;
  // the ROOT node is shared by both subtrees!
  leftParts.add(root);
  rightParts.add(root);
  // look at all of the immediate children of the ROOT node
  root.findTreeChildrenNodes().each(function(child) {
    // in what direction is this child growing?
    var dir = child.data.dir;
    var coll = (dir === "left") ? leftParts : rightParts;
    // add the whole subtree starting with this child node
    coll.addAll(child.findTreeParts());
    // and also add the link from the ROOT node to this child node
    coll.add(child.findTreeParentLink());
  });
}
/* Copyright 1998-2014 Northwoods Software Corporation. All Rights Reserved. */

body {
  font-family: sans-serif;
  font-size: 13px;
}

p {
  max-width: 700px;
}

p.box {
  border: 1px solid #BBB;
  padding: 4px 4px 6px 4px;
}

p.warning {
  background-color: #FCD5CD
}

.diagramContainer {
  border: solid 1px blue;
}

pre {
  font-size: 9pt;
}

.footer {
  text-align: right;
  font-size: 10px;
}


/* new: */

#sample {
  margin-left: 0px;
}

#menu {
  white-space: nowrap;
  overflow: hidden;
  border: 1px solid #DDD;
  padding: 4px;
  margin-right: 5px;
  background-color: #F9F9F9;
  width: 120px;
  float: left;
}

#sections {
  list-style-type: none;
  font-size: 13px;
  padding: 0px;
  margin: 0px;
  line-height: 1.3em;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a li {
  color: #0645AD;
}

a li:hover,
a li:focus {
  background: #CEDFF2;
}

a li.selected {
  background: #1E90FF;
  color: white
}

.index {
  margin-top: 0px;
}

#sample p,
#navindex,
#navtop,
.footer {
  display: none;
}
<script src="https://gojs.net/latest/release/go.js"></script>
<script src="https://gojs.net/latest/assets/js/goSamples.js"></script>
<div id="sample">
  <div id="myDiagramDiv" style="background-color: white; border: solid 1px black; width: 100%; height: 300px"></div>
  <div id="objInfo"></div>
</div>

The items when printed in the console looks like this enter image description here

I am trying to access the Items however it is not possible.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Santosh
  • 35
  • 1
  • 5

2 Answers2

0

Iterate an object by key, using Object.keys(theObject’), not theObject.length. Or put your items in an array instead.

Object.keys(theObject).forEach( key=> {theObject[key]})

Also, you have asynchronous calls, so when you log or access your items, the objects have not been fully created.

As proof, put a set timeout around this code, and then it works as expected.

setTimeout(()=>{
  document.getElementById("objInfo").innerHTML = "<br> Items Length : " + items.length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys Length : " + Object.keys(items).length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys: " + JSON.stringify(Object.keys(items));
  }, 1000);
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • Object.keys(items) is returning empty array. However when I created it as a Global Variable in chrome console then I am able to iterate through and retrieve the values. – Santosh Sep 13 '18 at 10:26
  • You have asynchronous calls. Replace your code with snippet I provided. – Steven Spungin Sep 13 '18 at 14:08
  • @Santosh Your library should either accept a `callback function`, or return a `promise` after rendering is complete. Check the documentation. – Steven Spungin Sep 13 '18 at 14:16
0

Please check for the valid object as if (typeof(obj[propt]) === 'object') and then use iteraters like Object.keys(obj).forEach(function(key,index) {...}

SaviNuclear
  • 886
  • 1
  • 7
  • 19
  • Object.keys(items) returning an empty array and the typeof items is Object. However when I created it as a Global Variable in chrome console then I am able to iterate through and retrieve the values. – Santosh Sep 13 '18 at 10:24
  • Please try https://stackoverflow.com/questions/2226007/fetching-all-javascript-global-variables-in-a-page – SaviNuclear Sep 13 '18 at 10:44