What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop.

Below is the data I am working with:

vm.memberDetails={
    "member": [
        {
            "firstName": "HARRY UTTWO",
            "lastName": "POTTER",
        }
    ],
    "User": [
        {
            "memberId": 7586671,
            "customerId": 7586671,
            "customerStatus": "T",
            "firstName": "HEMOOINE",
            "lastName": "POTTER",
        },
    ]
}

vm.mockData = {
    "data": [{
        "memberNo": 7586671,
        "suffix": "A"
    }]
}

The challenge I am facing involves comparing memberId and retrieving the name from the first set of data. I attempted to use angular.forEach but only managed to retrieve one value during looping using

vm.memberDetails.User[0].firstName
.

Controller:

angular.forEach(vm.memberDetails.User, function (value1,key1) {
    angular.forEach(vm.mockData, function (value2,key2) {
        if (value1.memberId === value2.memberNo) {

            vm.some= vm.memberDetails.User[0].firstName;
        }
    });
});
return vm.some;

Any assistance on this matter would be highly appreciated. Thank you.

Answer №1

Seems like you need to access the data array from vm.mockData by updating the line

angular.forEach(vm.mockData, function (value2,key2) {
to
angular.forEach(vm.mockData.data, function (value2,key2) {

angular.forEach(vm.memberDetails.User, function (value1,key1) {
    angular.forEach(vm.mockData.data, function (value2,key2) {
        if (value1.memberId === value2.memberNo) {
            vm.some= vm.memberDetails.User[0].firstName;
        }
    });
});
return vm.some;

Answer №2

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
</head>
<body ng-controller="mCon">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.7/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('mCon', function(){
            var vm = this;
            vm.memberDetails = {
         "member": [{
          "firstName": "HARRY UTTWO",
          "lastName": "POTTER",
         }],
         "User": [{
          "memberId": 7586671,
          "customerId": 7586671,
          "customerStatus": "T",
          "firstName": "HEMOOINE",
          "lastName": "POTTER",
         }, ]
        }
        vm.mockData = {
         "data": [{
           "memberNo": 7586671,
           "suffix": "A",
         }
         ]
        }
        angular.forEach(vm.memberDetails.User, function (value1,key1) {
            angular.forEach(vm.mockData.data, function (value2,key2) {
                if (value1.memberId === value2.memberNo) {
                    vm.result= vm.memberDetails.User[0].firstName;
                }
            });
        });
        return vm.result;
        })

    </script>
</body>
</html>

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

How to extract a value from a span input textbox using Vue?

I just started using Vue and I'm attempting to create an auto-growing input. I've realized that it's not possible to create a real <input> element that adjusts its size based on its content and allows for value modifications using v-mo ...

Error: The function pathRegexp is not defined

While attempting to conduct tests on my project with jest, I encountered an error code that seems unrelated to the actual testing process. It appears to be more of a dependency or Node Express compatibility issue. `● Test suite failed to run TypeError: ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

What could possibly be causing my app to exhaust CPU resources on Mozilla Firefox?

I have created a unique game application for Facebook. Currently, the app is not optimized with AJAX technology, resulting in multiple server requests causing high CPU usage (specifically in Firefox) which slows down the overall performance of the app. Alt ...

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...

Retrieve the location within the parent mesh

In my scenario, I have a series of meshes organized in a hierarchy as follows: Scene -scene.add(SpaceMesh) -SpaceMesh.add(ShipMesh) SpaceMesh is currently in motion within the scene. However, ShipMesh remains stationary. When I request th ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...

Sorting rows dynamically with jQuery Tablesorter

I've been struggling to find a solution for my specific issue. I need to have a static row in a large table that will not sort or move, allowing for repeated headers. Can anyone offer assistance with this? $("#dataTable").tablesorter({ ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

How can we use Mongoose .find to search with an array stored in req.params and respond with an array containing each value along with its

It would be great if a user could input multiple tags in a search field, and have them separated client-side (before making the .get call) to send over ajax with each keypress. While testing the API with Postman on the server-side, if the .get method retu ...

What could be the reason that a basic click function fails to locate the selector?

I have created a quick JavaScript module that opens an image and fades out a container to reveal the image. The HTML markup for the image looks like this: <div style="margin-bottom:1px;" class="rsNavItem rsThumb front"> <di ...

Retrieving information from a JSON file and displaying it in an HTML table through an asynchronous

I need to retrieve data from a server and display it in an HTML table. The server contains an array of weather forecast information as shown below. [{"date":"19\/08\/2020","weather":"Sunny","temperatur ...

Converting a boolean value to a boolean type in a CSHTML file

In my cshtml file, I am retrieving the value from the server code. It's a boolean field that returns a boolean value. Order="@Model.OrderModel.IsToday" I attempted to convert it to JSON using @Model.OrderModel.IsToday.ToJson(), but it seems to be tr ...

When attempting to retrieve a data object using a Vuex action, I encounter an "Uncaught (in promise) TypeError" when trying to access the data within the object

Recently, I've been diving into Vuex and its actions for fetching data. While everything seems to be working smoothly - accessing the films object, selecting films from it - I encounter an error when trying to access specific data within a film. Vuex ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

Glimmers of white light on Phonegap occur during data-ajax="false" events

Within my Phonegap html/js app, I am experiencing white blinks when switching between pages on both Android and iOS. Despite using Angular and jQuery, all links have data-ajax="false" to prevent ajax or transitions (even after removing jQuery, the issue pe ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

Discovering the names of files in a directory with Angular

Looking for a solution in Angular JS within a ModX app to retrieve file names from the gallery package every time it is updated. Is there a way to achieve this using Angular? I've been searching for Javascript solutions to this issue, but most of the ...