Question

The following works great to retrieve multiple selection Person and Group fields:

url: xurl+"/_api/web/lists/getbytitle('"+xlist+"')/items/getById('+xid+')?$select=Approvers/Name,Reviewers/Name,Informed/Name&$expand=Approvers,Reviewers,Informed"

Then what? I want to set the retrieved values in a variable or array...

var x=data.d.Name; // doesn't work, even for single value entries

and then proceed to set a form field with the retrieved value(s)...

$("input[title='Approvers']").val(x); // need proper field type, not input

Suggestions? Looking at the request in browser I can see all the properties I want, just can't pull them out and put them in variables.

UPDATE

The next step after my successful call should check to see if any users are defined as Approvers before performing any related actions. Below works for a single user but not if multiple users are defined in in multi-person column.

if (data.d.Approvers != undefined) {

nor this

if (data.d.Approvers.results.length>0 {

nor this

$.each(data.d.Approvers.results, function (index, item) {console.log("hello");});

console log error for multi:

console.log(data.d.results);

Uncaught TypeError: Cannot read... property 'Approvers' of undefined at Object.success...

Was it helpful?

Solution

The returned data is a collection:

data.d.Approvers.results.length

To get the first item:

data.d.Approvers.results[0]

Or the first user's name:

data.d.Approvers.results[0].Name

I have a REST tester for SharePoint that's useful for testing these kinds of things.
https://techtrainingnotes.blogspot.com/2017/04/a-sharepoint-rest-api-tester-with-ajax.html
https://github.com/microsmith/SharePointRESTtester

OTHER TIPS

It looks like the results array is not present if there are no users in the field, and it is present if there are one or more users. So you could just do:

// if results is not present on Approvers it will be undefined, which
// evaluates falsy, so it won't ever enter if if block if it's not there

if (data.d.Approvers.results) {
    data.d.Approvers.results.forEach(function (approver) {
        // do something with the approver here
        console.log(approver.Name);
    }
}

Here's a blog post I found that explains a bit about what evaluates truthy and falsy.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top