Why is Angular.forEach only giving back one result?

 $scope.$watch('selectedPoll', function(newValue, oldValue){
             if(newValue !== oldValue) {

               $scope.arrayResult.q1 = [];
               $scope.arrayResult.q2 = [];
               $scope.arrayResult.q3 = [];

               angular.forEach($scope.selectedPoll.questions, function(value, key) {
                   if (key) {
                        $scope.arrayResult = [];

                        var newArrayYes = [];
                        var newArrayNo = [];

                        for (var i = 0; i <    $scope.selectedPoll.survey_data.length; i++) {

                        if ($scope.selectedPoll.survey_data[i][key] === "YES") {
                        var resultOfqYes = newArrayYes.push($scope.selectedPoll.survey_data[i]);
                        }

                        if ($scope.selectedPoll.survey_data[i][key] === "NO") {
                        var resultOfqNo = newArrayNo.push($scope.selectedPoll.survey_data[i]);
                        }
                        }

                         $scope.arrayResult.push({
                        value: resultOfqYes, color: "#46BFBD", highlight: "#5AD3D1",
                        label: "Yes"
                        });

                        $scope.arrayResult.push({
                        value: resultOfqNo, color: "#F7464A", highlight: "#FF5A5E",
                        label: "No"
                        });

                       $scope.arrayResult[key] = $scope.arrayResult;

                     return $scope.arrayResult[key];
                   }
               });
               }
           });
    });

I am encountering an issue where only the data for the last object in selectedPoll.questions is being returned instead of getting three data sets as intended. Although console.log statements inside the 'if' statement show that it is executed for each object, the angular.forEach method seems to be returning only one dataset. I'm unsure why this discrepancy is occurring and how to fix it to get three separate data sets for each object processed by the angular.forEach method.

Answer №1

Each time you start a loop, $scope.arrayResult is being defined as an empty array, erasing any previous values that were stored in it.

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 Filter Fields in AngularJS Based on a Start Date and End Date?

Hey everyone, I'm trying to filter items based on the start and end dates using the daterange functionality in my meanjs app. I've tried multiple approaches but haven't found a solution yet. If anyone knows how to do this, please help me out ...

Challenges with removing and adding controllers in Angular versions 1.2 and above

I am currently in the process of migrating my app from Angular 1.2 to 1.3 and I am encountering an issue with the different behaviors of the removeControl and addControl functions. Within my directive, I have implemented a functionality that escapes regis ...

Disable the second tab within an Angular md-tabs component

Are there any attributes in angular material md-tabs that can be used to disable a tab, similar to what is available in Bootstrap? $scope.tabs = [{ title: 'Dynamic Title 1', content: 'Dynamic content 1' }, { title: 'Dy ...

"Bringing the power of JavaScript to your WordPress

I have set up a wordpress page and integrated some JavaScript into it. When working in wordpress, there are two tabs on a page where you can input text - 'Visual' and 'Text'. The 'Text' tab is used for adding HTML and scripts ...

Converting from Jquery to pure JavaScript and the process through which the interpreter searches the DOM for elements

I'm curious about the internals of JavaScript and how it handles certain queries. Specifically, I have a question regarding retrieving images with "flowers" in their src attribute using JQuery. The following JQuery code will do just that: $("img[src ...

Exploring the Power of Merging HTML with JavaScript in Shopify

Here is a snippet of code that I am grappling with: <div id="next-shipment"></div> var date = new Date(); // today using client's timezone date.setDate(date.getDate() + 1); // move to tomorrow date.setUTCHours(11,0,0,0); // set time using ...

Extract the #id parameter from the URL using jQuery

Suppose I have a URL similar to this http://localhost/sites/fh/index.php#second. My goal is to extract the id from the end of the URL and save it in a variable container for later use in an if else statement within jQuery. What would be the best approach ...

disabling focusOnSelect in slick.js arrow controls

I am currently using the slick.js menu with focusOnSelect: true. However, I have noticed that when I click on the left and right arrows, the colors of the divs are also changing. Is there a way to prevent this color change when clicking on the arrows? Can ...

Tips for postponing 'not found' error until the data has finished loading in Vue.js

I am accessing the following route: http://site.dev/person/1 The structure of my component is as follows: // PeopleComponent.vue <template> <div> <template v-if="person == null"> <b>Error, person does not exist.</b& ...

Compare several objects or arrays based on a selected array and combine them into a single object containing all matching elements from the selected array

selection = ["A", "lv3", "large"] Data = [{ id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " medium", }, id:2, title:"this is test 1", category:"C ...

Struggling to install dependencies in Node.js

I've been diving into the world of node js and recently completed a tutorial on creating a chat application. Everything was going smoothly until I hit a roadblock in one of the steps. In an attempt to troubleshoot, I downloaded the source code of the ...

What is the best way to target a specific selector within a JQuery script when dealing with multiple dropdown fields within the same form?

I have a form with 4 choice fields, but my jQuery code is only capturing one field. How can I modify the code to capture all the other fields and extract their values? Additionally, I have applied the Select2 plugin to these fields. Can someone provide gu ...

Vue 3's click event handler does not recognize $options.x as a valid function

I'm encountering a perplexing issue. I am currently in the process of creating a Wordpress plugin using Vue, but unfortunately, I am unable to establish functionality for the @click event. <script> export default { name: "App", me ...

Unexpected behavior with Javascript selectedIndex

The code I have should display the 'yestext' div when 'Yes' is selected in a dropdown box. However, this functionality is not working as expected. The issue seems to be with the JavaScript function, but it's unclear what exactly is ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

Navigating the routeProvider with a bookmarkable GET api call: Best practices

Below is my route configuration: .config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', {templateUrl: '/partials/search.html'}). when('/about', {t ...

The HTML and script tags are failing to connect

I recently started learning angularjs by watching the Egghead.io videos. However, I encountered an issue where I couldn't link my JavaScript page to my HTML page. my-index.html <!DOCTYPE html> <html> <head> <title>Angular ...

Passing a value to a component to delete a table row in ReactJS using Material UI

My task is to delete a specific table row after clicking. I have two components and have already written a function, handleDelete(), to remove a row from the table. The issue is that whenever I click, it always deletes the last row instead of the one I cli ...

I'm facing an issue while attempting to fetch an API. I'm not certain what is lacking in my code, but the console is showing an error on

While troubleshooting my code, the console pointed out an error in line 15 of my javascript. However, I am having trouble identifying what exactly is causing the issue. The button I designed in HTML does not seem to be fetching the API facts as intended, ...

What are the distinctions in how jQuery behaves when an element is assigned to a variable versus in Javascript?

I've noticed that when I assign a jQuery element to a variable, it doesn't match the element in a comparison. However, if I assign a JavaScript element, it does... test1 = $(".the_div"); console.log(test1 == $(".the_div")); // This logs false ...