jquerysharepointsharepoint-jsom

Get all lists and list items in a SharePoint site with JSOM


I have a SharePoint site and I want to use JSOM to get all lists, and get all items in each list.

I have tried this approach: Get all lists in the site, store their IDs For each list ID, get list items

Pseudocode is as such:

for each id in listOfIds(){
     executeQueryAsync( context with list ID passed in )
}

However, this approach presents a problem for me - the executeQueryAsync only takes the last ID in the listOfIds, presumably because the for loop iterates too fast.

What is the best approach for me to do to get all lists in my SharePoint site, and get all items for each of these lists? I can only use JSOM.


Solution

  • For that scenario:

    to use JSOM to get all lists, and get all items in each list

    the following example demonstrates how to accomplish it:

    var result = []; 
    var ctx = SP.ClientContext.get_current();
    var lists = ctx.get_web().get_lists();
    ctx.load(lists,"Include(Id,Title)");
    
    ctx.executeQueryAsync(
      function() {
    
           lists.get_data().forEach(function(list){
               var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
               ctx.load(items,"Include(Id,FileRef)");
               var listEntry = {
                 id: list.get_id().toString(),
                 title: list.get_title()
               }
               result.push({list: listEntry,
                            items: items}); 
           });
           ctx.executeQueryAsync(
           function() {
               //transform listitem properties
               result.forEach(function(item){
    
                   item.items = item.items.get_data().map(function(listItem){
                        return listItem.get_fieldValues(); 
                   });
               }); 
    
               console.log(JSON.stringify(result));
           },logError); 
    
    
      },logError);
    

    where

    function logError(sender,args){
       console.log(args.get_message());
    }
    

    Notes: