0

The following code outputs a comma separated array for the var cats. The array has six items as the list "banner" has two columns and three rows of items. I can access the array items in the first row by entering cats[0][0] and cats[0][1].

However, when I attempt to access the array items in rows 2 or 3 by doing cats[1][0],cats[1][1],cats[2][0] or cats[2][1] the array comes up empty.

Can someone help me understand why please?

<script src="/Utilities/jquery.min.js"></script>
<p style="font-size:20px;" width="500px;" id="Ptask"></p>
<script>

SP.SOD.executeOrDelayUntilScriptLoaded(retrivetasklistitems, 'SP.js');


var colltaskListItem;
var listItemArray = [];
var cats = [];
var tasks;


        function retrivetasklistitems() {
            var clientContext = new SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('banner');
    
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(
                '<View><Query><Where><IsNotNull><FieldRef Name="Url"/></IsNotNull></Where></Query></View>'
            );

            this.colltaskListItem = oList.getItems(camlQuery);
            clientContext.load(colltaskListItem);

            /* execute the query to get the loaded items */
            clientContext.executeQueryAsync(
                /* onSuccess Function */ 
                Function.createDelegate(this, this.OnQuerySucceeded), 
                /* onFail Function */ 
                Function.createDelegate(this, this.onQueryFailed)
            ); 
    
        }

        function OnQuerySucceeded(sender, args) {

            var count = 0; // for directory list
            var listItemEnumerator = colltaskListItem.getEnumerator();

            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                var title = oListItem.get_item('Title');
                var url = oListItem.get_item('Url');


            var categories = [title, url];
                
            listItemArray[count] = new Array(2);
            for (var i = 0; i<listItemArray[count].length; i++) {

                if(categories[i] == null || categories[i] == undefined) {
                    listItemArray[count][i] = " ";
                } else {
                    listItemArray[count][i] = categories[i];
                }
            }
            count++;

            var cats = listItemArray;

            tasks = "<p>" + cats[1][1] + "</p>" + "<br />";

            }
            $("#Ptask").html(tasks);
            }

            function OnQueryFailed(sender, args) {
                alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
            }
</script>
0

You are trying to access an array element before it is added to an array. To be more specific, cats[1] refers to the second element in your array. So, naturally, you'll get an error when you try to access it when only one element is created:

// cats[1] does not exist yet:
tasks = "<p>" + cats[1][1] + "</p>" + "<br />";

You might want to access your cats array using the count variable in this way:

tasks += "<p>" + cats[count][1] + "</p>" + "<br />";
count++;

This is your code with some modifications

var colltaskListItem;
var listItemArray = [];
var cats = [];
var tasks = ""


function retrivetasklistitems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('banner');
    clientContext.load(oList);
    clientContext.executeQueryAsync();

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><IsNotNull><FieldRef Name="Url"/></IsNotNull></Where></Query></View>'
    );

    colltaskListItem = oList.getItems(camlQuery);
    clientContext.load(colltaskListItem);
    clientContext.executeQueryAsync(
        /* onSuccess Function */
        Function.createDelegate(this, this.OnQuerySucceeded),
        /* onFail Function */
        Function.createDelegate(this, this.onQueryFailed)
    );

}

function OnQuerySucceeded(sender, args) {
    console.log("Success!");
    var count = 0; // for directory list
    var listItemEnumerator = colltaskListItem.getEnumerator();


    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var title = oListItem.get_item('Title');
        var url = oListItem.get_item('Url');
        console.log(title, url);

        var categories = [title, url];

        listItemArray[count] = new Array(2);
        console.log("listItemArray[count].length",listItemArray[count].length);
        console.log("count",count);
        for (var i = 0; i < listItemArray[count].length; i++) {
            console.log("categories", categories[i]);
            if (categories[i] == null || categories[i] == undefined) {
                listItemArray[count][i] = " ";
                console.log("listItemArray[count][i]", listItemArray[count][i]);
            } else {
                listItemArray[count][i] = categories[i];
                console.log("listItemArray[count][i]", listItemArray[count][i]);
            }
        }
        
        tasks += "<p>" + listItemArray[count][1] + "</p>" + "<br />";
        count++;
        console.log();

    }
    $("#Ptask").html(tasks);
}

function OnQueryFailed(sender, args) {
    alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

retrivetasklistitems();
2
  • Thank you Denis! With your help I looped through and created two separate arrays that solved my problem. Your code example was hugely helpful. Again, thank you so much! – bryan0920 May 2 at 0:41
  • @bryan0920, could you please accept the answer if it helped? – Denis Molodtsov May 2 at 1:40
0

This is happening because you are overriding value of var cats & var tasks each time in while (listItemEnumerator.moveNext()) loop.

You should not do that. You should declare cats & tasks variable outside of loop & append (instead of overriding) the value to cats & tasks each time in loop.

3
  • Thank you for responding Ganesh. I declared the variables like you suggested (and added it to the code above). I still can access individual array items. If I set cats to cats[0][1] I will get a list item from the first row. If I set cats to cats[1][1] (shown above) the item is empty. If set it to cats to cats it comes back with all six items separated by commas. – bryan0920 May 1 at 15:28
  • 1
    I can still see the var cats is declared again inside while loop in your edited question. Also, why are you creating array of array? You can easily bind the data to DOM in while loop without creating complex array. Check examples here & here – Ganesh Sanap May 1 at 16:10
  • 1
    This code is being used to build a banner ad system so it is important that I be able to add items to arrays. Instead I took the individual columns and made arrays out of them. Your post was very helpful and gave me the idea to place the individual column items into separate arrays. Thank you. – bryan0920 May 2 at 0:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.