The Rest-API does not support groupby functionality but we can achieve this by using CAML query in Rest-API call.
To achieve above functionality we will create one custom list called "Employee".
- Add two column i.e Name(SingleLine of Text), Department(Choice Field).
- Department choice column can have value i.e. IT,HR,Ops,Others
Your Employee list like this.
Create HTML file to show the value on page using groupby on Department column.
- <head>
- <script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js">
- </script>
- <script type="text/javascript" src="http://win-9uqiqjpidc3:9999/sites/test/Shared%20Documents/js/CAMLCAll.js"></script>
- </head>
- <div id="camlQueryBind"></div>
Rest Call using CAML Query
- $(document).ready(function () {
- console.log("In the ready!");
-
- groupBy1();
- });
- function groupBy() {
-
- var viewXml = {
- ViewXml: "<View>" +
- "<Query>" +
- "<GroupBy Collapse =\"TRUE\" GroupLimit =\"100\">" +
- "<FieldRef Name=\"Department\">" +
- "</FieldRef>" +
- "</GroupBy>" +
- "</Query>" +
- "</View>"
- }
-
-
- var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
-
-
- $.ajax({
- url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Employee')/GetItems(query=@v1)?" +
- "@v1=" + JSON.stringify(viewXml),
- type: "POST",
- dataType: "json",
- headers: {
- Accept: "application/json;odata=verbose",
- "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
- },
- success: function (data) {
-
- console.log(data.d.results);
- renderHTML(data);
- },
- error: function (data) {
-
- console.log("Error======>" + data);
- }
- });
- }
- function renderHTML(data) {
- var camlhtml = "<table><tr><td>ID</td><td>Name</td><td>Department</td></tr>"
- $.each(data.d.results, function (index, value) {
- camlhtml += "<tr><td>" + value.ID + "</td><td>" + value.Name + "</td><td>" + value.Department + "</td></tr>"
- });
- camlhtml += "</table>";
- $('#camlQueryBind').html(camlhtml);
- }
The above performs the following actions.
function groupby() is used to call the caml query using rest api
- Note in query we used GetItems instead of items as it's mandatory while calling caml query in rest api.
- It should be POST request.
- The caml query should be encoded in between this tag <View><Query>....</Query></View>
function renderHTML(data) is used to display the data by performing groupby on department.
- $.each is used to iterate the result.
- .html is used to bind the result with id #camlQueryBind
The result should look like this after completing the above steps.