Looping through an array and consistently returning the final value

When iterating through an array, I am trying to retrieve different data for each object in the array. However, I keep getting the same data repeated multiple times. For example, if I have 3 candies, 2 coffees, and 4 candy bars in my billBodies array, the result shows as 4 candy, 4 candy, 4 candy. I hope someone can assist with this issue. I have tried searching for similar problems but haven't found a solution yet...

 for (let bill of dataOfBillHeader.billBodies) {
        console.log(dataOfBillHeader)
        console.log(this.productToShowOnView)
      
        
        this.productToShowOnView.cipher = bill.product.cipher;
        this.productToShowOnView.name = bill.product.name;
        this.productToShowOnView.measure = bill.product.measure;
        this.productToShowOnView.count = bill.product.count;
        this.productToShowOnView.price = bill.product.price;
        this.productToShowOnView.id = dataOfBillHeader.id;
        this.productToShowOnView.count = bill.count;
        this.productToShowOnView.quantity = bill.quantity;
        this.productToShowOnView.discount = bill.discount;
        this.productToShowOnView.discountAmount = bill.discountAmount;
        this.productToShowOnView.totalPrice = bill.totalPrice;
        console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
        
        const newBasket = this.productsInBasket;
        this.productsInBasket.push(this.productToShowOnView);
        this.productsInBasket = [...newBasket];
        this.cd.detectChanges();
      }

Answer №1

Instead of repeatedly pushing the same object reference, which is this.productToShowOnView, why not use a local constant? It would make the code more concise. Also, if you want to convert data formats from one product format to another, you can try this optimized version:

const newBasket = [...this.productsInBasket];

for (let bill of dataOfBillHeader.billBodies) {
  const product = { 
    // combining properties
    ...bill.product,
    ...bill,
    id: dataOfBillHeader.id, // assigning common id
  };

  newBasket.push(product);
}

this.productsInBasket = newBasket;
this.cd.detectChanges();

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

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...

Comparing jQuery Elements

As per the jQuery documentation, it is stated that "Not All jQuery Objects are Created ===." The documentation also points out an important detail about the unique nature of each wrapped object. This uniqueness holds true even if the objects were created ...

Ember application experiencing trouble displaying Facebook Like Box

I’m currently facing an issue with integrating the like box into our ember app, specifically in a template named about. The problem arises when users enter the ember app from a different route, instead of directly accessing the about route. In such cases ...

Get the selected value from a dropdown list in Angular after populating the options

I am working with a model within an Angular module. $scope.employee = {} $scope.countries={} $scope..employee.Country_id = 10 $scope.employee.City_id = 50 Next, I am binding two select elements in the following way: $http.get("/api/initdataapi/GetCountr ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

Confusion arises when Java encounters an out-of-bounds index while dealing

Imagine you have a String temp = "efgh"; System.out.println(temp.substring(0,4)); // out of range, no exception System.out.println(temp.substring(0,5)); // out of range, exception thrown What causes this discrepancy? ...

Executing a callback after updating two-way binding values in an AngularJS component

myApp.component('example', { template: '<button type="button" ng-click="$ctrl.click()">click me</button>', bindings: { value: '=', callback: '&' }, controller: function () { this.cli ...

Exclude child rows from row count in DataTable

I have successfully implemented a feature on my datatable where child rows are toggled when a parent row is clicked. Here is the code I used: $(function() { $('tr.parent') .css("cursor","pointer") .attr("title","Click to expa ...

Customizing the appearance of the Google Maps API info window

I recently made some updates to our app's map feature by replacing our standard generic icons with smaller, more aesthetically pleasing ones. However, I've run into an issue where the new icons are not as tall as the old ones, causing the associa ...

Button placed within a jade table cell

I'm struggling to make a button appear in each row of the table. I am new to working with Jade and Node.js, so I can't seem to figure out why it's not showing up. Here is my Jade file: html head body table.table.table(border='1 ...

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

Angular 8 utilizes JavaScript for its programming language

Looking for a solution in JavaScript - check out: codepen.io/skovtun/pen/VwLvXPB Struggling to find an equivalent for Angular 8+. I want the center block to maintain a fixed width of 1200px, and automatically compress when the left, right, or both sideb ...

Determine the path of the file that triggered the execution of another file

I am looking to retrieve the file path of the file that executed another file. first.js const second = require("./second.js"); exports.run = () => { second.run(); } second.js exports.run = () => { let executedPath; // <-- ? con ...

Python method for removing specific index pairs from an array

I have a list of 10 numbers and I am interested in performing the following: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and would like to calculate the differences between alternating elements like so: differences = [numbers[1] - numbers[0], numbers[3] - n ...

Guide to transform an array into an ArrayObject in PHP using data from a JSON file

I've retrieved data from an external JSON file and it is structured as shown below: [ {"serial": 991, "name": "hello"}, {"serial": 993, "name": "world"}, {"serial": 994, "name& ...

The system is unable to access the properties of an undefined object, resulting in the error message "Unable to

I am encountering an issue while working on a project using nextjs, nodejs, and MongoDB. I am attempting to create an API within the pages/API path but keep receiving undefined errors. How can I resolve this? Thank you for your help. require("dotenv") ...

Carousel-item height in Bootstrap 4.6

I am facing an issue with a component in Angular 14 using Bootstrap v4.6: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div cl ...

Using an external file to handle the joining of a Socket.io room upon an HTTP request in an

I am finding myself in a state of confusion with this Node.js, Angular 13, and Socket IO situation. To start off, let's assume that all necessary information is being stored in a database, such as roomId, roomOwner, username, and so on. Now, let&apos ...

Maintain the dimensions of the dragged object when moving it across another object in a React application

I'm currently developing an application that allows users to rank different sentences by using a drag and drop feature in React. However, I have encountered an issue where the size of the dragged items changes when they interact with other items of va ...

How can I route to a page with URL parameters in Next.js?

I'm currently working with Next.js and TypeScript, and I need to figure out how to navigate to a different page while including URL parameters. Can anyone provide guidance on how to achieve this? For instance, if my current URL is http://localhost:30 ...