1

I'm having trouble with javascript recursion. Here is the code

_parseJson: function($object, $j_array) {
 for (i = 0; i < $j_array.length; i++) {
 var $el = document_designer.createElement($j_array[i]);
 $object.append($el);
 if ($j_array[i].elements.length > 0) {
 this._parseJson($el, $j_array[i].elements);
 }
 }
}

Both functions (parseJson and createElement) are under the object called "document_designer". Here is the createElement

createElement: function(n) {
 var $element = $('<' + n['tag'] + '/>');
 document_designer.oi++;
 if (n.id == null) {
 $element.attr('id', '____element' + document_designer.oi);
 }
 document_designer.processElement($element, n); // you may ignore this line
 return $element;
}

processElement function is not having problems. You may even ignore that line

document_designer._parseJson(document_designer.$preview, json_element)
// $preview is an created object in the `body`

and my parent JSON is : http://www.jsoneditoronline.org/?id=c99c77938e5edf91996e4bb267fd09b1

Root elements are creating and first main's sub childs but other root element's sub elements are not creating

asked Oct 13, 2016 at 12:23
9
  • 1
    What's the problem you're having? Commented Oct 13, 2016 at 12:26
  • Root elements are creating and first main's sub childs but other root element's sub elements are not creating Commented Oct 13, 2016 at 12:27
  • @ahmetertem, please provide a sample of your json. Commented Oct 13, 2016 at 12:29
  • @autoboxer jsoneditoronline.org/?id=c99c77938e5edf91996e4bb267fd09b1 Commented Oct 13, 2016 at 12:29
  • @autoboxer It's at the link he provided. It's really long. Commented Oct 13, 2016 at 12:29

1 Answer 1

3

you forgot the var in

for (i = 0; i < $j_array.length; i++) {

So you are using the same global i for all calls

change to:

 for (var i = 0; i < $j_array.length; i++) {

BTW , I like your code.

answered Oct 13, 2016 at 12:39
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you pal. I didn't even think about it can be... I appreciate it
@ahmetertem Imagine this happening in a large JS file.Very hard to find.
I posted just problemmed parts :) My file is already 500+ lines. Thanks again dude

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.