Exploring the capabilities of indexing an array within an array in Nativescript

I am working with JSON data retrieved from an API and trying to figure out how to index an array inside an array using Nativescript.

JS: cart [{
JS:   "_id": "5d3988cd287bad2943686920",
JS:   "userid": "11E76234942299FCC13FFA163EDC2079",
JS:   "products": [
JS:     {
JS:       "product_ID": "102",
JS:       "price": 20,
JS:       "quantiy": 2
JS:     },
JS:     {
JS:       "product_ID": "103",
JS:       "price": 20,
JS:       "qty": 3
JS:     },
JS:     {
JS:       "product_ID": "104",
JS:       "price": 20,
JS:       "qty": 3
JS:     }
JS:   ]
JS: }, {
JS:   "_id": "5d399ec8f8514f2a9a68da30",
JS:   "userid": "11E76234942299FCC13FFA163EDC2079",
JS:   "products": [
JS:     {
JS:       "product_ID": "102",
JS:       "price": 20,
JS:       "qty": 3
JS:     }
JS:   ]
JS: }]

I need help with a function that will increment the quantity for each product:

  incrementQty(product_ID) {
        for (let i = 0; i < this.cart[i].products.length; i++) {                  
                        this.cart[i].products[i].qty++;              
           }  
    }

this.cart[i].products.length; currently shows only 3 products.

The goal is to increment the quantity for each row in the array. How can I achieve this?

Answer №1

If you want to update the functionality of your incrementQty method, consider adding two parameters: _id and product_id. By utilizing Array.filter, you can efficiently filter through the cart array based on these identifiers.

const cart = [{
   "_id": "5d3988cd287bad2943686920",
   "userid": "11E76234942299FCC13FFA163EDC2079",
   "products": [
     {
       "product_ID": "102",
       "price": 20,
       "qty": 2
     },
     {
       "product_ID": "103",
       "price": 20,
       "qty": 3
     },
     {
       "product_ID": "104",
       "price": 20,
       "qty": 3
     }
   ]
 }, {
   "_id": "5d399ec8f8514f2a9a68da30",
   "userid": "11E76234942299FCC13FFA163EDC2079",
   "products": [
     {
       "product_ID": "102",
       "price": 20,
       "qty": 3
     }
   ]
 }];

 const incrementQty = (id, productId) => {
   const item = cart.filter(obj => obj._id === id)[0];
   const selectedProduct = item.products.filter(obj=> obj.product_ID === productId)[0];
   Number(selectedProduct.qty++);
 };

incrementQty('5d3988cd287bad2943686920', '102')
console.log(cart);

Furthermore, it seems like there is a typo in one of the properties of the product with an id of 102. It should be corrected to qty instead of quantiy.

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

I am facing an issue with saving my file on Heroku using Node.js. However, the file is being saved successfully on the local file system

I am currently developing a basic file uploader application using Nodejs. The files are being successfully saved to the local storage in an 'upload' directory, but after deploying the app to Heroku, I encountered an error as shown in this https:/ ...

how to enhance Request type in Express by adding a custom attribute

In my quest to create a custom middleware function in Node.js using TypeScript, I am facing an issue where I am trying to save a decoded JSON web token into a custom request property called 'user' like so: function auth(req: Request, res: Respo ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

Ways to verify if an array is multi-dimensional

I'm in the process of writing a code to determine if n is the highest number in the array A. If it is, return True, if not, return False. However, I am struggling with how to handle the two different conditions when the value is multidimensional or un ...

Please exclude any files with the name npm-debug.log.XXXXXX in the .gitignore file

Is there a way to exclude this file from the repository using .gitignore? https://i.stack.imgur.com/mK84P.png I am currently working on Gitlab. I have attempted the following: https://i.stack.imgur.com/2kN21.png Appreciate any help in advance ...

Is there a way to configure ESLint so that it strictly enforces either all imports to be on separate lines or all on a single line?

I am currently using ESLint for TypeScript linting. I want to set up ESLint in a way that requires imports to be either all on separate lines or all on a single line. Example of what is not allowed: import { a, b, c, d } from "letters"; Allo ...

Is it necessary to sanitize input fields manually in Angular 6?

Is it necessary for me to manually sanitize all user inputs, or does Angular handle this process automatically? In my login form, the data is sent to the server upon submission. Do I need to explicitly sanitize the data, or does Angular take care of sanit ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

How can Symfony 2 and PHP be used to compare differences between objects within arrays?

In my project using Symfony 2.7, I have created a form that returns an array of objects when submitted. I am looking to compare this array with the existing data in the table. Here is how the form is set up: $builder ....... ->add('my_o ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

VSCode prioritizes importing files while disregarding any symbolic links in order to delve deeper into nested node

I'm encountering a problem with VSCode and TypeScript related to auto imports. Our application includes a service known as Manager, which relies on certain functions imported from a private npm package called Helpers. Both Manager and Helpers make us ...

Ways to prevent altering values in ngModel

I am working on a component in Angular 5 where I am trying to write unit tests to ensure that when the component is disabled, it should not be possible to set a value to its model. However, even after disabling it, I am still able to change the value. [ ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Is there a distinction between pointers and arrays in the C programming language?

I am currently developing a small C program for number manipulation purposes, and I need to pass arrays between functions. Should these functions accept and return pointers? Here is an example implementation (acknowledging its potential inefficiency): in ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

Exploring the Features of Angular 6 through Interface Properties

Is there a way to add a description attribute to a property, similar to the data descriptions in dot net? For example: interface ModuleStatus { [Description "Module state"] moduleStateSymbol: string; [Description "Module type"] moduleTypeS ...

Passing an array by reference in C++: Step-by-step guide

I have been perfecting my skills in C++ and this is the code I've been working on. Could someone help me figure out how to modify ArraySortToMedian() so that it uses pointer notation instead of array notation to handle the array? Despite several atte ...

How to toggle element visibility when hovering in Angular?

I've set up an angular material card that includes a close button (marked with an "x"). My goal is to initially hide the "x" button and only display it when hovering over the card. Here is the code snippet for the card: <mat-card> <mat- ...