Domanda

I am trying to loop through my SharePoint list items retrieved using REST API but I get the following error:

Uncaught TypeError: Cannot read property 'ID' of undefined

function onQuerySucceeded(data) {
    var items = data.d.results
    console.log(items)
    var listItems = ''
    for (var x = 0; x <= items.length; x++) {
        listItems += '<tr>'
        listItems += '<td>' + items[x].ID + '</td>'  //<---Error here
        listItems += '<td>' + items[x].ID + '</td>'
        listItems += '<td>' + items[x].ID + '</td>'
        listItems += '<td>' + items[x].ID + '</td>'
        listItems += '</tr>'
    }
    document.getElementById("service").appendChild(listItems)
}

Any help would be much appreciated.

È stato utile?

Soluzione

To me it looks like you are getting an error because you are letting your indexing variable reach the full length of the results array:

for (var x = 0; x <= items.length; x++) {

Arrays use a zero-based index, so the last possible index is actually one less than the "length" of the array. Try changing that to:

for (var x = 0; x < items.length; x++) {

Also, if the error is happening on the very first pass through the loop, it's possible that you had no results from your query. If that's the case, data.d.results will be an empty array, and even index 0 will be undefined. As Ganesh Sanap suggested, try putting a check in to make sure you have results. I would go even one step further than that check, to also check the length of the results array and make sure it's not empty:

if (data.d && data.d.results && data.d.results.length > 0) {

This is why I personally prefer to use forEach loops rather than explicit for loops whenever possible, because forEach loops very gracefully handle the case when the array to be iterated over is empty.

Altri suggerimenti

Try using this code:

function onQuerySucceeded(data) {
    if(data.d && data.d.results) {
        var items = data.d.results;
        var listItems = "";

        for (var x = 0; x < items.length; x++) {
            listItems += '<tr>';
            listItems += '<td>' + items[x].ID + '</td>';
            listItems += '<td>' + items[x].Title + '</td>';
            listItems += '</tr>';
        }
        document.getElementById("service").appendChild(listItems);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top