title: JavaScript building JSON asynchronous and dynamicall
body: <p>I have some trouble with asynchronous JavaScript. I call a function within a jQuery AJAX call, and in this function there are probably other asynchronous methods calls. I stuck in there on the moment.</p>
  
  <p>Here I have the code snippet which is called by the jQuery AJAX function: Here I build dynamically a JSON object.</p>
  
  <pre><code>function getJSONObjektList() {
      //MainJSON
      var jsonObjekt = {};
      jsonObjekt.ObjektId = [];
      jsonObjekt.Selected = [];
  
      doc = XYZ.GetCurrentDocument();
      //probably also an asynchrounous call
      doc.GetAllObjects(function (objects) {
          for (var i = 0; i &lt; objects.length; i++) {
              var obj = objects[i];
              var id = obj.id;
              var caption = obj.caption;
              var type = obj.type;
              var my = obj.my;
              console.log("[obj:" + obj + " id:" + id + " caption:" + caption + " type:" + type + " my: " + my + "]");
  
              //liste alle verfuegbaren  Objekte auf 
              jsonObjekt.ObjektId.push(id);
  
              if (type === "Statusbox") {
                  doc.GetObject(id, function () {
                      var statusboxInhalt = this.Data.Rows;
                      //inner JSON object                        
                      var utilJSONObjekt;
  
                      for (var j = 0; j &lt; statusboxInhalt.length; j++) {
                          // make sure to re-initialize so we don't update the same reference
                          utilJSONObjekt = {};
                          utilJSONObjekt.SelectedObjektId;
                          utilJSONObjekt.SelectedObjektWerte = [];
  
                          var inhalt = statusboxInhalt[j];
                          console.log("Name: " + inhalt[0].text + " Wert: " + inhalt[2].text);
  
                          utilJSONObjekt.SelectedObjektId = inhalt[0].text;
  
                          var valAr = inhalt[2].text.split(",");
                          for (var k = 0; k &lt; valAr.length; k++) {
                              utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
                          }
                          jsonObjekt.Selected.push(utilJSONObjekt);
                          //**till here is the jsonObject not null or empty, there are some values in there**
                      }
                  });
              }
          }
      });
      //**but on the return statment is the jsonObjekt empty**
      return jsonObjekt;
  }
  </code></pre>
  
  <p>Have someone some tips how can I solve my problem, or how can I make JavaScript best asynchronously working.</p>