Is there a way to determine if an object has been included using angular.forEach in AngularJS?

I am facing an issue while attempting to add objects to the $scope.orderitems. My goal is to update the quantity property of the object in $scope.orderitems if it already exists, rather than adding another object. However, every time I call the additem function, I encounter an error stating that orderitems is not defined.

Below is my code:

HTML

<input type="text" ng-model="item.name">
<button type="button" ng-click="additem(item)">

<ul>
    <li ng-repeat="orderitem in orderitems">
        <p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
    </li>
</ul>

JS

app.controller('OrderCtrl', function($scope) {
    $scope.orderitems = [];
    
    $scope.additem = function(data) {

        angular.forEach(orderitems, function(orderitem) {
            if (orderitem.id === data.id) {
                orderitem.qty = orderitem.qty++;
            } else {
                data.qty = 1;
                $scope.orderitems.push(data);
            }
        });
    };
});

Answer №1

Check out this functional demo: http://jsfiddle.net/rodhartzell/hbN4G/

HTML Code Snippet

<body ng-app="app">
    <div ng-controller="OrderCtrl">
    <input type="text" ng-model="item.name">
        <button type="button" ng-click="additem()">add</button>

    <ul>
        <li ng-repeat="orderitem in orderitems">
            <p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
        </li>
    </ul>
</div>

AngularJS Controller Code

var app = angular.module('app', []);

app.controller('OrderCtrl', function($scope) {

    $scope.orderitems = [{name: 'foo', id:1, qty:1}];
    $scope.additem = function() {
        var exists = false;
        var data = {
            id : $scope.orderitems.length + 1,
            name: $scope.item.name,
            qty: 1
        }
        angular.forEach($scope.orderitems, function (item) {
            if (item.name == data.name) {
                exists = true;
                item.qty++;
                return false;
            }
        });
        if(!exists){
            $scope.orderitems.push(data);
        }

    };
});

Answer №2

var orderList = [];
function addItemToOrder(data) {
    var item = null;
    angular.forEach(orderList, function(orderItem) {
        if (orderItem.id === data.id) {
            item = orderItem;
            return false;
        }
    });
    if (item == null) {
        item = {
            id: data.id,
            qty: 0
        };
        orderList.push(item);
    }

    item.qty++;
}

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

Tips for Choosing Specific Ranges in Your Findings

Can data retrieval be customized to show only specific columns based on preferences, such as 1, 5, 8, 11, and 23? function enterRepName(){ var ui = SpreadsheetApp.getUi(); var input = ui.prompt("Please enter your rep name.",ui.ButtonSet.OK_CAN ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

Utilizing REACT to extract values from deeply nested JSON structures

Currently, I am utilizing react to display information from properties stored in a nested JSON. While I can successfully render properties like 'name' and 'id' that are not nested, I encounter an issue when trying to access a nested pro ...

Breaking down arrays using the JADE Template Engine

Currently, I am utilizing the JADE template engine in conjunction with ExpressJS. I am attempting to pass an array to my JADE template like so: var data = { "labels" : ["Label 1", "Label 2"] }; res.render('index', {data: data}); The struct ...

Revolutionizing Wall Updates with NodeJS

After developing a NODEJS application utilizing Jade as the templating engine, Express, and a MySQL database, I want to create a new page where users can share text snippets. Underneath this input area is a div called "Wall" that should update dynamically ...

Using the ternary operator in a jQuery event

I am looking for a solution to have a button trigger different functions based on the value of a variable. It appears that the ternary operator does not work with a jQuery event trigger. var color = "blue"; $(document).ready(function(){ $('#bot ...

Developing personalized field validation in Angular

I'm encountering an issue with my code on Plunkr where the form.name.$invalid is always true, even though I expected it to be false based on Angular's documentation. It seems like the $invalid value is being set by the javascript code where ctrl. ...

The auto-complete feature is malfunctioning after retrieving input suggestions from a PHP file

My goal is to achieve the following: 1. Create a list of suggestions with same labels but different descriptions. 2. Upon selecting an item from the list, the input field of another item should change to the corresponding description of the selected item. ...

ngroute enables the ability to handle multiple URL parameters

I am struggling with implementing routing functionality in Angular. Here is my goal: I have a main page that links to dashboard.html and another page called buildings.html. The buildings page can be accessed with various parameters such as id, type, and c ...

Finding a specific object within an array of objects by searching through a key value pair

In my collection, I have an array of objects structured as follows: [{ "businessunit": [{ "Area": [{ "Asset": [{ "Wells": { "Well": "Well 11" }, "name": "Field ...

Sending variable boolean values to a VueJS component

How can I assign dynamic properties to a VueJS Component using VuetifyJS? Below is an example of VuetifyJS code that constructs a select field element: <div id="app"> <v-app id="inspire" style="padding: 10px; "> ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

Exploring ways to specifically select predefined strings by defining a regex parameter in angular-ui-router

I need to restrict access to a specific state in my angular-ui-router based on the parameter being one of the following strings: "site1" "site2" "site3" Here is my current state configuration: $stateProvider.state("error", { url: '/error/{sub: ...

Why is this Array undefined?

When trying to loop through an Array until it's fully filled and displaying a loading dialog, I keep encountering the error message: this.events[0] is undefined ngOnInit() { this.initMethod(); if(this.events[0].start == this.books[0].date_fro ...

How to alphabetically sort an AngularJS ng-repeat table that contains a special character ':' in the values?

I am utilizing angularjs ng-repeat to organize my records by clicking on table headers. I came across a perfect example that functions flawlessly. Here is the code snippet: <th ng-repeat="header in headers"> <a ng-click="toggleSort($index)"&g ...

Cutting through arrays in PHP

Is there a way to filter an array with another boolean array in PHP? <?php $arr=array(0=>12,1=>'name',2=>1.21,4=>'color'); $select=array(1=>true,2=>true,3=>true,4=>false); //$new=$arr[$select]; ?> In P ...

Determining the exact position of an image with resizeMode set to 'contain' in React Native

I am currently developing an object detection app using React Native. The process involves sending an image to the Google Vision API, which then returns a JSON file containing coordinates and sizes of objects detected within the image. My goal is to draw r ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...

Accessing data returned from JSON in JQuery beyond the code block required

Is there a way to access returned JSON data outside of the JQuery getJSON method? For example: var price = ""; $.getJSON("../JSONDeliveryPrice", null, function (data) { price = eval(data.price); }); console.log(price); Unfortunately, this code does not ...

Is the Order of a JSON Array Dependable?

When working with JSON, it's clear that relying on the ordering of key-value pairs may not be reliable. For instance, a JSON parser could interpret { "someKey" : "someValue", "anotherKey" : "anotherValue", "evenAnotherKey" : "evenAnotherV ...