Filtering SharePoint Object Collections using PnP JavaScript library

PnP-JS-Core library contains the number of extensible methods and properties. By using that we can achieve the various actions in a simple code. To know more about this library component, visit the below links,

Simplified JavaScript Library for SharePoint

PnP-JS-Core Library

SharePoint has lot of building blocks in collections which are used to form a SharePoint site. Those are used in manage the contents, generate reports based on contents & settings, etc… To manage or reporting the contents, we have to insert sorting or filtering functionality to the collections.

Based on 1.0.1 version of PnP-JS-Core library, following are the collections available for developers to use in SharePoint add-ins or applications,

contenttypes fields Files folders
items lists navigation sitegroups
siteusers usercustomactions userprofiles Views
webs

Note: Links will be updated soon on each object to show more details

PnP-JS-Core Component is built using the REST API, so the same syntax for filtering & sorting can be used in this library extensions.

To apply the filter in REST API, we can use the below format to filter the items from the collection,

http://sharepointsite.com/_api/web/lists?$filter=<PropertyName condition PropertyValue>

Use the below REST API endpoint example to get the content type enabled lists,

http://sharepointsite.com/_api/web/lists?$filter=AllowContentTypes eq true

The same way, we can use the same syntax to apply filter in PnP JS Core library, because it is developed on top REST API.

Below are some example PnP-JS-Core snippets to filter the objects based on each properties from the collection.

      1. Filter Content Type enabled lists
        //Show the content type enabled lists
        $pnp.sp.web.lists.filter('AllowContentTypes eq true').get().then(function(result) {
            //Add your code to display the collection results
        });
        
        
      2. Filter Documents Libraries from the Lists
        //Show the document libraries
        $pnp.sp.web.lists.filter('BaseTemplate eq true').get().then(function(result) {
            //Add your code to display the collection results
        });
        
        
      3. Filter Blog sites from the subsites
        //Show the blog sites from the collection of subsites
        $pnp.sp.web.webs.filter("WebTemplate eq 'BLOG'").get().then(function(result) {
                //Add your code to display the collection results
        });
        
        

Note: Replace the below line for displaying the results.

//Add your code to display results with the below code to display the object title
for (var i = 0; i < result.length; i++) {
        console.log(result[i].Title);
}

This PnP JS library simplifies the code implementation and reduces the developer effort too.

Happy learning :)

Leave a Reply

Your email address will not be published. Required fields are marked *