REST api postCatgory showing as object

I was able o successfully use $expand for two lists
$.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

Open in new window

But when I try to access postCategory, I get an object.
for(var i =0; i < data.d.results.length; i++) 
		{		
			var imgStatus = (dateDiff(data.d.results[i].Created));
			if(imgStatus == "New")
			{
				imgCategory = "<img src='http://isaacsogunro.com/blog/Images1/yellowNew.png' alt='New'>";
			}
		    //bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='#' onClick='openModal("+data.d.results[i].ID+");return false;'>"+data.d.results[i].Title+"</a>",/*data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
			bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='http://isaacsogunro.com/blog/Lists/Posts/Post.aspx?ID="+data.d.results[i].ID+"'>"+data.d.results[i].Title+"</a>",data.d.results[i].PostCategory,/*data.d.results[i].Category,data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
		}

Open in new window



Here's what i get for postcategory
1postcategory.JPG
Any ideas?
LVL 5
IsaacSharePoint Client Side DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rajendra ShekhawatSolution ArchitectCommented:
Hi,

PostCategory is an object with nested categories.
I tested your code and modified it to write it to console.

Attached code snippet.
Please test and let know, in case of any issues.

I hope it helps.

Cheers,
Raj

<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js'> </script>
<script type='text/javascript'>

var url = 'http://c4968397007/sites/blog';
var listname = 'posts';

$.ajax({

        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

function complete(data)
{

   for(var i =0; i < data.d.results.length; i++) 
   {		
    console.log(data.d.results[i].Created);
    console.log(data.d.results[i].Title);
 
      for(category in data.d.results[i].PostCategory.results) {
            console.log(data.d.results[i].PostCategory.results[category].Title);
      }  //end of category loop
   }  //end of loop
}  //end of function

</script>

Open in new window

0
IsaacSharePoint Client Side DeveloperAuthor Commented:
I got the following error: SCRIPT5009: 'category' is undefined

I then added 'category' to my rest:
items?$select=Created,Title,NumCommentsId,ID,Category,PostCategory/Title&$expand=PostCategory",

After that, I get error
0
Rajendra ShekhawatSolution ArchitectCommented:
Hi,

Category is not the field. PostCategory is the field. List of Categories is inside PostCategory object.
Code Snippet shared gives you list of categories.

Cheers,
Raj
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

IsaacSharePoint Client Side DeveloperAuthor Commented:
When I had the following
items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory"

Open in new window


I got this error:
SCRIPT5009: 'category' is undefined
0
IsaacSharePoint Client Side DeveloperAuthor Commented:
Here's my whole code:
Here's what i'm trying to achieve:
As you can see, the Category column is 0. It needs to show the categories that was assigned to that post. ie: javascript, SharePoint, HTML 5, etc.

Two lists are being used, Posts and Categories.  Category column in the Post  list is a lookup into Categories
Category
	$(document).ready(function(){
		$('#blog').DataTable();

		getListItems('http://mysite/blog','Posts','complete', 'failure','timeout');
	});

//Change code to use this - http://datatables.net/examples/advanced_init/events_live.html
function getListItems(url, listname, complete, failure, timeout) {

    // Executing our items via an ajax request
	
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

	function complete(data) 
	{		
		var bldRow=$('#Iblog').DataTable({
			"order": [[ 0, "desc" ]],
			"pagingType": "full_numbers"
		});
				
		var imgCategory=" ";
		for(var i =0; i < data.d.results.length; i++) 
		{		
			var imgStatus = (dateDiff(data.d.results[i].Created));
			if(imgStatus == "New")
			{
				imgCategory = "<img src='http://mysite.com/blog/Images1/yellowNew.png' alt='New'>";
			}		   
			bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='http://mysite.com/blog/Lists/Posts/Post.aspx?ID="+data.d.results[i].ID+"'>"+data.d.results[i].Title+"</a>",data.d.results[i].NumCommentsId,/*data.d.results[i].Category,data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
		}
	 }
	function failure(data) {
	 alert("Operation failed.");
	 }	 
}	

	function dateDiff(spCreated)
	{
		var createdDte = new Date(spCreated);
		var todayDate = new Date();
		var timeDiff = Math.abs(todayDate.getTime() - createdDte.getTime());
		var days = Math.ceil(timeDiff/(1000*3600*24));
		var status = (days > 30) ? "Old":"New";
			
		return status;
	}

	function dateFormat(spCreated)
	{
		var createdDte = new Date(spCreated);
		var newFormat = (createdDte.getMonth()+1)+"/"+(createdDte.getDate()+"/"+createdDte.getFullYear());
		
		return newFormat;
	}
	
	 function openModal(blogID) {
		var pageUrl = 'http://mysite.com/blog/Lists/Posts/Post.aspx?ID='+blogID;
		var options = { url: pageUrl, width: 650, height: 650 };

		SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);

	 }

Open in new window

0
Rajendra ShekhawatSolution ArchitectCommented:
Hi,

Were you able to get the results for community count ?

Cheers,
Raj
0
IsaacSharePoint Client Side DeveloperAuthor Commented:
Hi Raj,

No. Actually, the image that has the Category shouldn't be 0, it should be categories (javaScript, HTML, SharePoint, etc.)
0
Rajendra ShekhawatSolution ArchitectCommented:
Hi,

Please send me complete code with html ( datatables.net etc. ). I would try to fix it.
My Email - rajendra.shekhawat@gmail.com
My Skype - rajendra.shekhawat

Cheers,
Raj
0
IsaacSharePoint Client Side DeveloperAuthor Commented:
Ok. I just sent you an email with all the information you need.
Thanks so much for doing this.
0
Rajendra ShekhawatSolution ArchitectCommented:
Hi,

As per the code shared, here is the working html and javascript.

Html 
-----------------


<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="http://understandsp.com/blog/SiteAssets/DataTables-1.10.6/media/css/jquery.dataTables.css" />

<script type="text/javascript" src="http://understandsp.com/blog/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://understandsp.com/blog/SiteAssets/DataTables-1.10.6/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="http://understandsp.com/blog/myBlogAssets/myBlog.js"></script>

<html>
<head>
	<title>myBlog</title>
<style>
/*table.dataTable {
    width:auto !important;
}*/
</style>

</head>
<body>

<table id="Iblog" class="display nowrap dataTable dtr-inline cell-border" cellspacing="0" width="750px">
	<thead>
		<tr>
			<th width="10px">Date</th>
			<th>Title</th>
			<th>Categories</th>
			<!-- <th>Comments</th> 
			<th>Category</th>
			<th width="5px">Status</th>-->
		</tr>
	</thead>
	<!-- <tfoot>
		<tr>
			<th>Date</th>
			<th>Title</th>
			<th># of Comments</th>
			<th>Category</th>
		</tr> 
	-->
	</tfoot>
	<tbody id="myBlogData">

	</tbody>
</table>

</body>

</html>


Javascript - 

	$(document).ready(function(){
		$('#blog').DataTable();

		getListItems('http://understandsp.com/blog','Posts','complete', 

'failure','timeout');
	});

//Change code to use this - 

http://datatables.net/examples/advanced_init/events_live.html
function getListItems(url, listname, complete, failure, timeout) {

    // Executing our items via an ajax request
	var test = url + "/_api/web/lists/getbytitle('" + listname + "')/items?

$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory"
	console.log(test);
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?

$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

	function complete(data) 
	{		
		var bldRow=$('#Iblog').DataTable({
			"order": [[ 0, "desc" ]],
			"pagingType": "full_numbers"
		});
				
		var imgCategory=" ";
		for(var i =0; i < data.d.results.length; i++) 
		{		
			var imgStatus = (dateDiff(data.d.results[i].Created));
			if(imgStatus == "New")
			{
				imgCategory = "<img 

src='http://understandsp.com/blog/Images1/yellowNew.png' alt='New'>";
			}		
  
  var categories = '';

	  for(category in data.d.results[i].PostCategory.results) {
            console.log(data.d.results[i].PostCategory.results[category].Title);
            categories = categories + data.d.results[i].PostCategory.results

[category].Title + ',';
      	 }  

console.log(categories);


			bldRow.row.add([dateFormat(data.d.results[i].Created), "<a 

href='http://understandsp.com/blog/Lists/Posts/Post.aspx?ID="+data.d.results[i].ID

+"'>"+data.d.results[i].Title+"</a>", categories]).draw();				

   
		}
	 }
	function failure(data) {
	 alert("Operation failed.");
	 }
	 
}	

	function dateDiff(spCreated)
	{
		//console.log(spCreated);
		var createdDte = new Date(spCreated);
		var todayDate = new Date();
		var timeDiff = Math.abs(todayDate.getTime() - createdDte.getTime());
		var days = Math.ceil(timeDiff/(1000*3600*24));
		//console.log(days);
		var status = (days > 30) ? "Old":"New";
			
		return status;
	}

	function dateFormat(spCreated)
	{
		var createdDte = new Date(spCreated);
		var newFormat = (createdDte.getMonth()+1)+"/"+(createdDte.getDate

()+"/"+createdDte.getFullYear());
		
		return newFormat;
	}
	
	 function openModal(blogID) {
		var pageUrl = 'http://understandsp.com/blog/Lists/Posts/Post.aspx?

ID='+blogID;
		var options = { url: pageUrl, width: 650, height: 650 };

		SP.SOD.execute('sp.ui.dialog.js', 

'SP.UI.ModalDialog.showModalDialog', options);

	 }

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
IsaacSharePoint Client Side DeveloperAuthor Commented:
Thanks a lot! That makes sense.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
REST

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.