0

I am using the SPService,
the method GetListItems.
I need to groupBy the result (distinct).
This is my code:

var CamlQuery = '<Query><GroupBy Collapse="TRUE"><FieldRef Name="nameA" /></GroupBy></Query>';
var CamlViewFields='<ViewFields><FieldRef Name="nameA" /></ViewFields>';

$().SPServices({
    operation: "GetListItems",
    async: false,
    webURL: siteURL,
    //CAMLRowLimit: "10",
    listName: "myLists",
    CAMLViewFields: CamlViewFields,
    CAMLQuery: CamlQuery,
    completefunc: function (xData, Status) 
    {      
        //do stuff
    }
});

but it is not working. I am using the right GroupBy Element as described on msdn.
Is there a way to do the GroupBy using the REST API?

1

Regarding grouping in SharePoint REST, according to Use OData query operations in SharePoint REST requests, Grouping is not supported.

One of the solution, is to apply grouping for the JSON results returned from REST endpoint.

Example

Suppose the following function for getting list items via SharePoint REST API:

function getListItems(url, listname, query, complete, failure) {
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data.d); 
        },
        error: function (data) {
            failure(data);
        }
    });
}

Then you could filter unique values from JSON array as demonstrated in answer Get unique results from JSON array using jQuery:

function groupBy(items,propertyName)
{
    var result = [];
    $.each(items, function(index, item) {
       if ($.inArray(item[propertyName], result)==-1) {
          result.push(item[propertyName]);
       }
    });
    return result;
}

The usage

getListItems('https://tenant.sharepoint.com/project','Tasks','?select=Title',
    function(items){    
       var taskNames = groupBy(items,'Title');
       console.log(taskNames);
    },
    function(error){
       console.log(JSON.stringify(error));
    }
);

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.