Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular).

In my PHP code, I have the following:

<?php
$cart = array(
    48131 => array(
        'size' => 'STANDARD',
        'qty' => 1,
    )
);

print_r($cart);

The value 48131 serves as the index, making it easy to delete items based on this key.

However, in my JavaScript implementation:

function addToCart() {
    this.cart = [];

    this.cart.push({
        id: this.id,
        size: this.size,
        qty: this.qty
    });

    console.log(this.cart);
}

When I use this function, I noticed that push method assigns keys starting from 0. I've been trying different approaches but can't seem to resolve this issue. Can anyone offer some guidance?

Answer №1

let myCart = {};
function addItemsToCart() {       
    myCart[this.id]= {
        size: this.size,
        quantity: this.qty
    };
   console.log(myCart);
}

Answer №2

Just follow these steps:

function addToCart() {
    this.cart = [];

    this.cart['72982'] = {
        id: this.id,
        size: this.size,
        qty: this.qty
    };

    console.log(this.cart);
}

Answer №3

It is important for the shopping cart on the angular side to contain an object. You can add an item to it in this way: var cart = {}; cart[id] = {prop1: val1, prop2: val2};

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

Create a new element by cloning the React component as an SVG named SomeSVG

I have a scenario where I am receiving an SVG as a prop in my child component. Once I receive it, I would like to manipulate it by adding some additional properties like this: {React.cloneElement(ReactSVGasProp, { className: class })} However, when I atte ...

I have been encountering an error consistently whenever I attempt to access the _id parameter in my angular front-end

EmployeeComponent.html: 11 ERROR TypeError: Cannot read property '_id' of undefined This is the error I encounter whenever I attempt to access the id in my front-end implementation using Angular. I have attempted incorporating ngIf, but unfo ...

The jQuery menu is malfunctioning in Internet Explorer due to the Document Mode being set to Quirks

I am encountering an issue where the below code is not functioning properly in Internet Explorer's document mode quirks. Each time I hover over the submenu, its length doubles unexpectedly. Can someone please provide assistance with this matter? < ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Tips for waiting for an event from a specific element in Playwright

Is there a way to await an event on a specific element using Playwright? Similar to page.waitForEvent, but focusing only on a particular element rather than the entire page. More information can be found in the documentation. ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

What is the reason that asynchronous function calls to setState are not grouped together?

While I grasp the fact that setState calls are batched within react event handlers for performance reasons, what confuses me is why they are not batched for setState calls in asynchronous callbacks. For example, consider the code snippet below being used ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

In JavaScript, the event.defaultPrevented property will never be set to true

I've been experimenting with events in my script, but I'm struggling to understand the functionality of event.preventDefault()/event.defaultPrevented: var e = new Event('test'); e.defaultPrevented; > false e.preventDefault(); e.d ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Experiencing difficulties with Magento operations

Currently facing an issue while attempting to set up Magento on my server. I have transferred all files from another server to mine, but now encountering an error. Could this be related to the symlinks I generated or is it caused by something else? Encoun ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...