I have an array that requires mapping objects and pushing into a new array

Here is the Array that needs to be processed:

[
    {
        "batchno": "B-PI1-1",
        "unitId": 341,
        "productName": "Bar Soap",
        "productProfileId": 3950,
        "qty": 148,
        "returnQty": "20",
        "rate": 10,
        "salesRate": 20,
        "unitName": "PC",
        "gross": 200,
        "net": 200,
        "remarks": "sxzxz"
    },
    {
        "batchno": "B-PI4-1",
        "unitId": 341,
        "productName": "Biscuit",
        "productProfileId": 3951,
        "qty": 700,
        "returnQty": "20",
        "rate": 10,
        "salesRate": 60,
        "unitName": "PC",
        "gross": 200,
        "net": 200,
        "remarks": "zxzxzx"
    }
];

The task at hand is to create a new array, making sure not to duplicate entries:

if (this.primengTableHelper.initialRecords.length > 0) {
    this.primengTableHelper.initialRecords.map((item: any) => {
        console.log('item', item);
        this.singleItem.batchNo = item.batchno;
        this.singleItem.unitId = item.unitId;
        this.singleItem.productName = item.productName;
        this.singleItem.productProfileId = item.productProfileId;
        this.singleItem.qty = item.qty;
        this.singleItem.returnQty = item.returnQty
        this.singleItem.rate = item.rate;
        this.singleItem.salesRate = item.salesRate;
        this.singleItem.unitName = item.unitName;
        this.singleItem.gross = item.net;
        this.singleItem.net = item.net;
        this.singleItem.remarks = item.remarks;
        this.createOrEditDamageStockDto.paymentNO = this.voucherNO;
        this.createOrEditDamageStockDto.invoiceDate = 
            this.maxInvoiceDateFilter.toString();
        this.createOrEditDamageStockDto.damageStockDetailsListDto
            .push(this.singleItem);
    });

Answer №1

Continuously pushing the same this.singleItem, a single object, during each iteration leads to multiple references pointing to the same object. Instead, ensure that a fresh object is created in every iteration. Utilize spread syntax over individual assignments:

        const newItem = {...this.singleItem, ...item};
        // Make other changes to `newItem` properties if needed...
        // ...
        // Push the new object:
        this.createOrEditDamageStockDto.damageStockDetailsListDto
            .push(newItem);

It may not pertain directly to your query, but these lines within the loop are redundant as they remain constant throughout each iteration:

    this.createOrEditDamageStockDto.paymentNO = this.voucherNO;
    this.createOrEditDamageStockDto.invoiceDate = 
        this.maxInvoiceDateFilter.toString();

Place these statements outside the loop since they do not change. Also, consider using .forEach instead of .map when the result is not utilized. However, you can employ .map to generate an array for assignment to

this.createOrEditDamageStockDto.damageStockDetailsListDto
. The suitability depends on whether the array exists before the loop and requires preservation.

Answer №2

It seems like the question is not fully clear to me. You currently have an array consisting of two objects. Are you looking to create a new array with three objects, where the third object is a duplicate of the second one? In that case, you can achieve this by leveraging the ES6 spread operator as shown below:

const startingItems = [
  {
    "id": 1,
    "name": "Item A"
  },
  {
    "id": 2,
    "name": "Item B"
  }
]

const itemsWithDuplicate = [
  ...startingItems,
  startingItems[startingItems.length - 1]
]

You may find more information on the topic here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_array_literals

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

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...

Do you find this unattractive? What are some ways to improve this unsightly JavaScript statement?

This code seems messy, how can I better structure this switch statement? function renderDataTypeIcon(dataType: string) { let iconName; switch (dataType) { case "STRING": //TODO - ENUM iconName = "text"; break; ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

What is the solution to fixing the Vue 2 error when using Node 12?

Issue with Node 12: It seems that there is an error related to the node-sass library in Node 12. Error message from Node: node-pre-gyp ERR! node -v v12.1.0 node-pre-gyp ERR! node-pre-gyp -v v0.10.3 node-pre-gyp ERR! not ok ...

Implementing Scroll-Activated Class with Vanilla JavaScript

I'm currently developing a Vue.js project and I want to implement a feature where a "back to top" button appears when the user scrolls beyond a certain point. However, I'm encountering an issue without using JQuery. Can you help me troubleshoot t ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

The Javascript Navbar is malfunctioning on Firefox

Currently, I am working on a horizontal menu that includes submenus. My goal is to use Javascript to display the submenu when a user hovers over the parent menu. I created a JSFiddle example, which seems to be experiencing issues in FireFox! However, it w ...

Breaking down setInterval IDs for their corresponding function parameters

I plan on running multiple setIntervals, and though there may be a more efficient way to do it, that's something I'll consider later down the line. Is there a method for achieving this? var a = setInterval(function(a){ console.log(a); c ...

Is there a method available to streamline the process of generating .json files for language translations?

Working with translation files can be a tedious task, especially when adding new keys for different languages. Making sure that each key is included in all the JSON files can lead to errors and repetitive editing. Is there a more efficient way to handle t ...

The Angular controller encountered an unexpected token

I have organized all my Angular controllers in one controller file. However, I encountered an issue when trying to print out a specific part of my object array at the end of a controller. Everything worked fine until I added a new controller after the cur ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Authorization in Confluence REST API

Currently, a user is logged in to Confluence; There is an external web application that saves attachments to a specific page. In order to make REST calls from the external app, I need the user's credentials for Confluence (which I do not have because ...

Retrieve the ID value of the paragraph that was clicked on using the right-click function

If I have text with this specific html markup: <p id="myId">Some text <span>some other text</span></p> Is there a way to retrieve the value of the id upon right-clicking on any part of the paragraph? Update: I'm simply pass ...

Browser lacks proper credentials for passport authentication

I'm currently learning how to incorporate user authentication using passport.js. I have successfully set up a basic passport "local" strategy on the server side, along with a single POST route for logging in users. When testing with insomnia, everythi ...

Warning: Promise rejection not handled, async/await is failing to resolve promise

After spending several days researching, I am unable to identify the root of the issue I'm facing. My GCloud web app is built on Express, utilizing bcrypt for password encryption, and Google Firestore in Datastore mode as the database. Below is my r ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

Elements on the page appear and disappear as you scroll down

Whenever my scroll reaches the bottom of element B, I want my hidden sticky element to appear. And when I scroll back up to the top of element B, the sticky element should be hidden again. Here are my codes: https://i.sstatic.net/J49dT.jpg HTML <htm ...

What is the reason behind having 3 watchers for 1 binding in AngularJS?

Take a moment to view the screenshot provided below https://i.sstatic.net/qLcem.png In the screenshot, it is evident that there are #3 watchers for a single binding. Would someone care to explain the reason behind this? P.S: I am utilizing AngularJS Ba ...