How to retrieve multiple person or group values in SharePoint using JavaScript

Names from my SharePoint list are stored with the field names 'People' and 'Responsible', added using a peoplepicker. These fields are of type 'person or group' in SharePoint. In my Service file, I have the following code:

    this.getPeople = function () {
    var deferred = $.Deferred();

    var restQueryUrl = appweburl + "/_api/lists/getByTitle('RisikoAnalyse')/items?$select=People/Title,Responsible/Title&$expand=People/Title,Responsible/Title";
    var executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: restQueryUrl,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data, textStatus, xhr) {
            deferred.resolve(JSON.parse(data.body));
        },
        error: function (xhr, textStatus, errorThrown) {
            deferred.reject(JSON.stringify(xhr));
        }
    });
    return deferred;
};

The 'People' field is a multiple value field, while 'Responsible' allows only one value. My controller contains the following code:

        $.when(SPService.getPeople())
        .done(function (jsonObject) {
            angular.forEach(jsonObject.d.results, function (obj) {
                $scope.peopleList.push({
                    people: obj.People.Title,
                    responsible: obj.Responsible.Title

                });
                //$scope is not updating so force with this command
                if (!$scope.$$phase) {
                    $scope.$apply();
                }
            });
        });

In this code snippet, I loop through all objects in 'jsonObject.d.results' and add them to the 'peopleList'. The code works for the single value 'Responsible' field but does not handle the multiple values in the 'People' field effectively. I need assistance on how to iterate over the objects inside the 'People' field and include multiple values in my 'peopleList'. Can anyone guide me on how to achieve this effectively?

Answer №1

When using the SharePoint REST service, you may encounter a User field that contains multiple values in JSON format:

{
   results: 
      [ { Title: "John Doe"}],
      [ { Title: "Jane Doe"}]
}

To extract the titles of these individuals, you can use the following code snippet:

var peopleTitles = item.People.results.map(function(p){ return p.Title});

Here is an adjusted example for a controller:

angular.forEach(jsonObject.d.results, function (obj) {
     var peopleTitles = typeof obj.People.results != 'undefined' ? obj.People.results.map(function(p){ return p.Title}) : [];
      $scope.peopleList.push({
           people: peopleTitles,
           responsible: obj.Responsible.Title
      });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

Errors occur when using jQuery Autocomplete alongside Angular HTTP

I have implemented an ajax autocomplete feature for my database using the jQuery-Autocomplete plugin. Below is my current code setup: HTML: <input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> Angular $scope.searchCustome ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...

Incorporating traditional Bootstrap styling directly into a React application without relying on the react-bootstrap library

My goal is to incorporate my existing bootstrap components into a React project without having to rewrite them to work with the react-bootstrap library. While I have successfully integrated the bootstrap CSS, I am facing issues with the functionality aspec ...

JavaScript function returning code

I am trying to create a JavaScript object with multiple functions, but I keep encountering an exception undefined is not a function Here is my JS code: var Cars = null; $(function () { Cars = function() { return { ...

Error message encountered: React hydrate TypeError - the function __webpack_require_.i(...) is not recognized as a

I encountered a webpack TypeError while attempting to use hydrate() in my index.js file. Strangely, the error does not appear when I use ReactDOM.render() instead of hydrate. My intention behind using hydrate was for server-side rendering. src/index.js i ...

Is the $scope and $$phase workaround consistently reliable in AngularJS for achieving the desired results?

When working with third-party tools and external DOM events in AngularJS, it's important to remember to use the $scope.$apply() method to apply changes. However, sometimes calling $apply while the scope is already digesting can cause an error. To avoi ...

Looking to perform an Ajax call to update a Rails model using HTML5 contenteditable, but encountering an issue where it creates a new

I am in need of assistance to update the plots of a story using HTML5 contenteditable feature. Below is the code snippet: Refer to file# for editing multiple plots <div id="editable" contenteditable="true"> <%= simple_format p.description %&g ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

Create a set of n randomly generated points, represented as latitude and longitude pairs, originating from the central point of a polygon while remaining within the boundaries

I am currently trying to plot data within a polygon (District), but unfortunately, I do not have specific coordinates for each of the data sources in that district. My goal is to accurately display all the results from a district within its boundaries, wh ...

The Ajax success function is failing to trigger after receiving a 200 network response

I have a basic HTML page that loads jquery 3.3.1 and an external script file called script.js. I am using a simple node http-server to serve the static page. The data.json file is also in the same folder as the HTML file. However, even though the network c ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

After Effects Script: Apply various character styles from main text to subtext

I'm currently working on an After Effects script that can transfer the style and text of a text layer to another text layer in a different comp. The script works perfectly if the parent text layer only has one style, but I need it to handle a situatio ...

Having trouble with sending an Incoming Slack hook message using Angular1's $http method

Here's the http request code snippet I'm using: $http({ method: 'post', dataType: 'json', data: { 'username': 'HiBye', 'icon_emoji': ':ghost:', 'channel': &a ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...

AngularUI Calendar event source which triggers a function with each change of view

In order to showcase the issue, let me explain my objective. I am in the process of developing a booking system using AngularUI Calendar. The problem arises when the calendar's performance noticeably deteriorates as the number of events increases (100 ...

Guide on incorporating database-sourced audio playback using buttons in PHP and HTML

Building my website with an audio player inside has been a bit challenging. I encountered an issue when trying to combine songs loaded from the database with a play button. My goal is to have the play button change when clicked and load the song from the d ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...