Exploring the AngularJS functionality of AngularForEach within nested arrays

I've just started diving into AngularJS and I'm facing some challenges with using angular.forEach... Specifically, I have a data object retrieved from my REST API...

My goal is to iterate through a nested array, look for a specific attribute, and if that attribute is set to true, retrieve another attribute from the item.

Here's an example of the array structure;

orderItem:  { 
    id: 159
    name: Empanadas (Choice of 2)
    description: Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella
    price: 700
    available: 1
    created_at: 2016-01-31 16:50:31
    updated_at: 2016-01-31 16:50:31
    menu_category_id: 41
    restaurant_id: 11
    menu_modifier_groups: 
        [  { 
            id: 9
            name: Choose 2 Empanadas
            instruction: null
            min_selection_points: 2
            max_selection_points: 2
            force_selection: 1
            created_at: 2016-02-01 01:03:35
            updated_at: 2016-02-01 01:12:23
            menu_item_id: 159
            restaurant_id: 11
                menu_modifier_items: 
                [  { 
                    id: 34
                    name: Diced Beef
                    price: 0
                    created_at: 2016-02-01 01:04:08
                    updated_at: 2016-02-01 01:04:08
                    menu_modifier_group_id: 9
                    restaurant_id: 11
                    menu_item_id: 159
                    selected: false
                 } ,  { 
                    id: 35
                    name: Smoked Salmon & Mozzarella
                    price: 0
                    created_at: 2016-02-01 01:04:37
                    updated_at: 2016-02-01 01:04:37
                    menu_modifier_group_id: 9
                    restaurant_id: 11
                    menu_item_id: 159
                    selected: true
                 } ,  { 
                    id: 36
                    name: Stilton, Spinach and Onion
                    price: 0
                    created_at: 2016-02-01 01:05:05
                    updated_at: 2016-02-01 01:05:05
                    menu_modifier_group_id: 9
                    restaurant_id: 11
                    menu_item_id: 159
                    selected: false
             }  ]
         }  ]
 }

My objective is to identify all menu_modifier_items that have selected set to true, retrieve their respective price values, sum them up, and then add the total to the original price of the orderItem.

Sum of all menu_modifier_items prices + orderItem price

$scope.calculatePrice = function(orderItem) {
    angular.forEach(orderItem, function(){
    });
}

Any assistance or guidance would be greatly appreciated.

Answer №1

Here is a possible solution for your request:

$scope.computeTotalPrice = function(order) {
   var totalPrice = 0;

   // Loop through each group of menu modifiers
   angular.forEach(order.menu_modifier_groups, function(group) {

      // Look at each individual menu modifier item in the current group
      angular.forEach(group.menu_modifiers, function(modifier) {

         // If the item is selected, add its price to the total
         if (modifier.isSelected)
            totalPrice += modifier.cost;
   });

   order.total = totalPrice; // Add the computed total to the existing order total
};

Answer №2

While not a direct response to your query, I lack the necessary reputation to comment on existing answers (apologies if this is not the correct protocol).

Learning Angular is valuable, but it's important to note that similar functionality can be achieved using native JavaScript functions as well, providing additional insight. The forEach function is inherent to arrays, so instead of:

angular.forEach(orderItem.menu_modifier_items, function(val) {...})

You could alternatively use:

orderItem.menu_modifier_items.forEach(function(val) {...})

For a more JavaScript-centric approach, there are other built-in functions that allow you to achieve the same outcome in a more functional manner by filtering out unwanted array values and consolidating the selected values into a single result:

var totalModifierAddOnsPrice = orderItem.menu_modifier_items.filter(function(group) {
    return group.selected; // excludes unselected groups
})
.reduce(function(itemA, itemB) {
    return itemA.price + itemB.price; // combines prices into one total value
});

The Mozilla Developer Network offers comprehensive documentation on this topic - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray

To clarify, while utilizing the angular forEach function is effective, the methods outlined above serve as informative alternatives.

Answer №3

Give this a shot

$scope.calculateTotal = function(selectedItem) {
var totalCost = selectedItem.price;
angular.forEach(selectedItem.options[0].items,function(option,index){
    if(option.isSelected == true) {
        totalCost += option.price;
    }
    if(index == selectedItem.options[0].items.length-1) {
        console.log(totalCost); //final cost
    }
});

}

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

Explore the world of textures transferring from Maya to Three.js

I'm looking to convert a Maya model to JavaScript for a simple model with textures. The conversion works fine, but the textures are not showing up. Here is my code: var loader = new THREE.JSONLoader(); loader.load( "models/t2.js", function(geometry) ...

Tips on managing PDF files from a Web API in AngularJS

I have implemented a Web API post method for generating a PDF: [HttpPost] [Route("api/pdf")] public HttpResponseMessage Post(CustomType type) { StreamContent pdfContent = PdfGenerator.GeneratePdf(); HttpResponseMessage response = new HttpResponse ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

Searching for the length of the greatest substring comprised of distinct characters in JavaScript

Seeking a solution to the problem of finding the longest sub-string within a string that does not contain any repeating characters. I am facing an issue with my code when trying to handle the input "dvdf". Below is the code that I have written: function ...

Angular.js: Utilizing ng-model for checkboxes

Here's the code for my project: <input type="checkbox" ng-model="variable"> In this scenario, the variable will hold either true or false based on the checkbox status. However, I want it to store "+" instead of true and "-" instead of false. W ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

"Is it possible for the package-lock.json file to not update when a package is removed from the

When I add a package manually to my package.json file and run npm install, the dependencies of that new package are updated in my package-lock.json. However, if I then delete that package from package.json and run npm install, the dependencies of that pac ...

Creating a clone of a JavaScript object based on an already existing JavaScript object

Can someone help me with this coding issue? var originalObject = { method1: function() { // Do something }, method2: ['a','b','c'], method3: 1234 } I am trying to create a new object based on the orig ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

servlet failing to send a response to ajax call

I am facing an issue where the servlet is not sending back a response to my AJAX code. Can someone please help me with this? Below is the HTML code, the output should be printed here: This is the AJAX code written in JavaScript: <script language="jav ...

Is there a way to interact with a DOM element through clicking and then pass it as a variable using PHP?

Is there a way to configure a table so that data from a specific row is sent to a PHP script and displayed in a section on the website when the user clicks on that row? I am looking to pre-fill a data entry form with information from a selected row, allow ...

"Revamping URLs in JHipster for a seamless user

I have a query that I'm unsure is feasible. I am attempting to eliminate the '#' from my jhipster website URLs, but it seems challenging in my code. For example: http://www.example.com/#/test -> http://www.example.com/test Is there an a ...

Placing a blank span after the highlighted text

Currently, I am developing a dictionary feature that allows users to select text and view the definition of the word or phrase by hovering over it for a second. It's a simple concept, but my implementation is quite basic so far. I'm using the mou ...

Continuously invoking a function until jQuery's .post method has completed loading

As I am diving into the world of jQuery framework, I encountered a situation where I used the readyState() function while working with AJAX in regular JavaScript to display a loading gif image. However, when transitioning to using jQuery's .post() met ...

Is there a way to use regex to selectively color JSON keys?

My goal in JavaScript is to extract all of the JSON keys using regular expressions. I am assuming that the JSON data will be formatted with each key-value pair on a new line, like this: { "name": "Jane", "age": 30, } In simple terms, I am looking ...

What is the best way to monitor the currentUser service for updates in my navigation controller?

My navbar has a "nav" controller that displays the current user's image. However, I'm facing an issue where the nav image does not update when the user changes their profile photo. Below is my service: 'use strict'; angular.module(&ap ...

What is preventing me from adding content to a <p> element?

I'm currently developing a ToDo list web application and I'm working on retrieving the information from 4 text boxes to create the content for each ToDo item. However, when I attempt to link the elements generated from the form, I encounter the ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

What is the best method for comparing the keys and values of two arrays?

I'm facing a challenge with two arrays that have similar keys and values. My goal is to create a new array containing only the values that are not present in the first array. I attempted to use the array_intersect function, but the outcome was unexpec ...