Modify the information being retrieved from a promise

Within my application, there is a service that the controller calls upon to retrieve an array of objects. However, not all of the data returned by this service is relevant to my needs. I am interested in extracting only specific information from the array. Is there a way to customize the structure of the returned array so that it contains only the necessary data?

For instance:

$scope.information = [];

var loadData = function() {
  var promise = myService.getData();
  promise.then(function(data) {
    $scope.information = data.Information;
  },
  function (dataError) {
    console.log(dataError);
  )};
};

In the given example, the data.Information array consists of objects with properties like:

{
  id: 1,
  name: 'joe',
  age: '21',
  hair: 'blue',
  height: '70',
}

However, for my controller's purpose, I am only interested in the 'id' and 'name' attributes, excluding the rest. It would be ideal to streamline the retrieval process by eliminating unnecessary details and preventing front-end bloat. Can I arrange the $scope variable to contain only the required data within the objects?

Answer №1

It seems like you are interested in applying a map function to the array. This means that for each element in the array, you want to transform it in some way. To achieve this, you can utilize the Array.prototype.map method. Here is a helpful link to the MDN documentation for more information.

For example:

$scope.information = data.Information.map(function(element) {
    return {
        id: element.id,
        name: element.name
    }
});

Answer №2

There are multiple ways to accomplish this task, but here is one simple approach:

$scope.info = [];

var fetchData = function() {
  var promise = myService.fetchData();
  promise.then(function(data) {
    $scope.info = data.Info.map(function(d) {
      return {
        id: d.id,
        name: d.name
      };
    });
  },
  function (dataError) {
    console.log(dataError);
  )};
};

(Keep in mind that I have not tested this code, so you may need to make adjustments as needed)

Answer №3

John's response offers a great illustration of post-fetch data filtering in action. In the project I am currently involved in, there are situations where calculating certain fields for records from our backend server via its REST API can be resource-intensive. This leads us to carry out similar operations as shown below:

var fetchData = function() {
  var promise = myService.retrieveData({fields: "name,id"});
  promise.then(function(data) {
    $scope.details = data;
    });
  },
  function (dataError) {
    console.log(dataError);
  )};
};

In this scenario, the service or backend takes charge of data filtering, allowing only essential information to be transmitted back to us. Considering implementing (or persuading the service maintainers to implement) such filtration mechanisms is an alternative strategy worth exploring.

Answer №4

If you want to sort through the information provided by the service:

app.service("myService", function("$http") {
    this.getData() = function() {
        return $http.get(url)
          .then(function(response) {
            return response.data;
        });
    };
    this.infoRetrieve = function() {
        var promise = this.getData();
        var newPromise = promise.then(function(data) {
            var information = data.Information.map(function(d) {
                return {
                    id: d.id,
                    name: d.name
                };
            });
            return information;
        });
        return newPromise;
    };
});

How to use this feature:

  var promise = myService.infoRetrieve();
  promise.then(function(information) {
    $scope.information = information;
  },
  function (dataError) {
    console.log(dataError);
    throw dataError;
  )};

By utilizing the .then method of a promise to send back data, a fresh promise is formed that resolves to the value of the returned information.

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

Vue.js is throwing a TypeError message stating that it is unable to read the property 'post' of undefined, despite the fact that vue-resource has been successfully

Alright, here's the issue: I'm encountering a TypeError and I can't figure out why. I have Vue-resource installed and imported Vue.use('vue-resource'); import {} from 'vue-resource'; in my main.js file. I've tried ...

I attempt to demonstrate to my users, but unfortunately, it doesn't seem to be successful

My console.log is showing "undefined" for my users even though I can see them in my State. This issue started happening after implementing Redux - previously, it was working fine without Redux. Take a look at the code snippet from UserManagement.js: funct ...

Tips for maintaining an exposed dropdown menu in the following page?

I'm working with a dropdown that contains <a> tags and is initially set to be hidden. There's also a caret next to the dropdown that rotates down when the dropdown is open. What I'm trying to achieve is keeping the dropdown open (caret ...

Handling Forms with Node and Express

I'm currently following a guide to create a node/express application using the jade template engine. I've encountered a 404 error when trying to submit a form. In my routing, I have this line: app.post('sign_up', sign_up); which is caus ...

The functionality of fetching website titles using Ajax/jQuery is experiencing some limitations

Below is a code snippet for a simple website title getter: $( document ).ready(function() { $("#title").click(function() { var SubURL = $("#input").val(); $.ajax({ url: "http://textance.herokuapp.com/title/"+SubURL+"/", complete: function(da ...

Triggering a Dialogflow Chat Window with a click on a Material-UI Floating Action Button in a ReactJS application

I have encountered an issue in my code where I am attempting to toggle the display of a Dialogflow Chat Window, <ChatWidget />, when a user clicks on the Material-UI Floating Action Button, <FloatingActionButton/>. The default state is set to f ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

Employing switch statements to match regular expressions in JavaScript

Could someone help me with converting my if statements to a switch statement for evaluating regex? I have been struggling to figure it out and would appreciate any guidance. Below is the code I have attempted: var username = $('input.username'), ...

Tips for Preventing or Eliminating Duplicate Random Numbers in PHP

As part of my form process, I send invoices to clients via email and our site email address ([email protected]). Each invoice is assigned a random number like #502689, generated using the PHP rand(99,999999) function. Avoiding repetition of these num ...

Firefox unable to play video recorded in Chrome

A video captured using the react plugin called, rico345100/react-multimedia-capture, was successfully recorded and uploaded to a server via Chrome. However, when attempting to play the same video in Firefox, it does not function properly. Interestingly, vi ...

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...

Display the text once using ng-repeat only if a certain condition is met

I am trying to display an element only once within ng-repeat. The issue with my code below is that the "Event of today" message is displayed every time an event starts today... This is my current code: <div class="line" ng-repeat="event in events"& ...

What are the steps to employ a query string to display a specific image?

If I understand correctly, I can utilize a query string and parse it to display certain information. How would I apply that concept to load a specific image? https://codepen.io/anon/pen/qYXexG <div id="gallery"> <div id="panel"> <img ...

Ways to alter a PHP variable with each AJAX request

Utilizing AJAX to dynamically add more content to an image gallery. I'm passing a PHP variable to dictate the current page number and other necessary data. Each time new data is fetched via AJAX, I want to increment the page variable by one to fetch ...

Adding an onload event to a popup window using Javascript

I am attempting to add an onload event to a popup window in the following way: var newPopup = window.open(PARAMS...); newPopup.onload = function() {window.opener.unlockObj(id);} The goal is to disable the button that launches the popup window until all o ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

What is the process for retrieving values from dynamic textareas using Vue JS?

Within the v-for loop, I am creating dynamic text fields. My dilemma now is how to retrieve the values of these inputs, as they are not a fixed number input so that I can assign their variables in the data(). This is how I am rendering the inputs: <i ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

Mongoose discovers an unexpected empty array

My task is to locate a SoldProduct with an intimeOrderNumber value of '3'. var query = { intimeOrderNumber: '3' }; However, my search result returns an empty array. SoldProduct.find(query, function(err, soldProducts) { if (err) { ...

How can you retrieve the value of a CSS file in Javascript and CSS?

Imagine there is an element with the class .selector. This class defines its style. Once the page has finished loading, some JavaScript code is executed - the specifics are not important. What matters is that the CSS properties have set the object's ...