-1

I can't populate jsTree because something is wrong with the array that I'm creating.

jsTree allows you to pass in JSON data, so I'm trying to format an array of objects that jsTree will like:

    var myAry = [];

    $(xml).find('group').each(function() {

      myAry.push({
        "id": $(this).find('GroupID').text(),
        "parent": "#",
        "text": $(this).find('GroupName').text(),

      });
    });

When I dump [myAry] to the console, it looks like a properly formatted Array, but jsTree doesn't like it. However, if I create an array manually, jsTree likes it:

  var testAry = [
                    {"id": "42", "parent": "#", "text": "Foo"},
                    {"id": "69", "parent": "#", "text": "Bar"},
                    {"id": "1", "parent": "#", "text": "Dolphin"},

    ];

What's going wrong in my loop?

enter image description here

NamedArray
  • 773
  • 3
  • 10
  • 25
  • 1
    How does your dumped my Ary compare to your testAry example? – Taplar Nov 08 '17 at 17:36
  • @Taplar I included the console output from Chrome. The content is the same, but its missing the count at the top along with [{...},{...},{...}] which led me to believe it was not formed correctly. – NamedArray Nov 08 '17 at 17:51
  • 1
    https://jsfiddle.net/q3s3o4ja/2/ Looks the same to me. – Taplar Nov 08 '17 at 17:51
  • 1
    https://jsfiddle.net/q3s3o4ja/3/ And they both seem to work. – Taplar Nov 08 '17 at 18:02
  • @Taplar I didn't give all the information. That code is part of an AJAX GET sucess function. Oddly enough the array takes a different form depending on where I establish/call it -- either inside or outside the AJAX function. Let me work on this some more and I'll reply. Thank you for helping me get this far. – NamedArray Nov 08 '17 at 20:20
  • @Taplar That each loop was of an AJAX call, and I was trying to access the array *outside* of the AJAX success function. My assumption is that there wasn't enough time for the array to be completely built yet: https://stackoverflow.com/questions/47189964/why-is-my-array-behaving-differently-outside-of-an-ajax-function-populating-js/47189990#47189990 – NamedArray Nov 08 '17 at 21:50

1 Answers1

-1

This may help (from jQuery docs):

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.

The method you're using accepts a selector argument, but you're passing it the name of a JSON object.

Try using $.each().

vashzak
  • 9
  • 1
  • 7