Get person display name from list via javascript
-
06-02-2021 - |
Question
I am facing problem that i cannot solve. I have a function which works properly but returns number id of user from sharepoint not display name. Here is the function:
function getItems() {
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Testiing')/items", // URL to fetch data from sharepoint list
method: "GET", //Specifies the operation to fetch the list item
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose" //It defines the content type as JSON
},
success: function(data) {
data = data.d.results;
//Iterate the data
$.each(data, function(index, value) {
if (value.Project_x0020_ManagerId !== null && value.Project_x0020_ManagerId == _spPageContextInfo.userId){
var html = "<tr><td>" + value.Title + "</td><td>" + value.Project_x0020_ManagerId + "</td>" + "<td>" + new Date(value.dates).toLocaleDateString() +"</tr>";
//can be removed later - getting items to console
console.log(this, value, data[index]);
$('.table tbody').append(html); }
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
}) }
Project_x0020_ManagerId is the name of the column of person type.
Can anyone advise how to solve this? or how to create function which would convert id to display name please?
I am using this function for filling html table element so it would be perfect with display names right away.
Thanks.
Solution
I'm guessing that the actual name of the column is "Project Manager", and that only through the data that you get from your REST request do you see the column with the internal name appended with "Id".
User columns in SharePoint are actually lookup columns to a user list. So in order to get values from the lookup item, you need to use $select
and $expand
in your REST query.
So you would want to try something like this:
/_api/web/lists/GetByTitle('Testiing')/items?$select=Project_x0020_Manager/Id,Project_x0020_Manager/Title&$expand=Project_x0020_Manager
to get the ID and display name (Title) of the user.
Keep in mind that if you use $select
, you will only get those columns back in the results, so the query above will return only the Project Manager field. If you need data from other fields from that list, you will have to include them in the $select
as well:
/_api/web/lists/GetByTitle('Testiing')/items?$select=Project_x0020_Manager/Id,Project_x0020_Manager/Title,OtherField1,OtherField2&$expand=Project_x0020_Manager
Also, if you do the $select
and $expand
to get the Project Manager data, you won't get that field back as value.Project_x0020_ManagerId
. You would access the data through value.Project_x0020_Manager.Id
and value.Project_x0020_Manager.Title
.