Add 1 to the count if the order ID is located in local storage

let items = JSON.parse(localStorage.getItem('cart')) || [];
let newItem = {};

$.each(items, function () {
    if (newItem.order_id == this.order.id) {
        newItem.order_id = '1';
        newItem.order_name = 'cake';
        newItem.price = '$1.10';
        newItem.qty = 1;
        newItem.qty = parseInt(this.qty) + 1;
    } else {
        newItem.order_id = '1';
        newItem.order_name = 'cake';
        newItem.price = '$1.10';
        newItem.qty = 1;
    }
});

items.push(newItem);
localStorage.setItem('cart', JSON.stringify(items));

Is there a way to adjust the quantity of an order when the order_id already exists in localStorage? The code snippet above adds another set of array objects even though the quantity part is correct.

Answer №1

To efficiently update the array value only when the id matches, it is best practice not to create a new object in this scenario.

Instead, modify the if statement in your code as follows:

$.each(arr, function(){
if(obj.order_id == this.order.id){
  this.qty = parseInt(this.qty) + 1; //Adjusting the quantity value
}

Additionally, make sure to push obj in the else block exclusively.

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

Angular's Conditional ng-if Error

Encountering an error link from Angular Js [1]http://errors.angularjs.org/1.2.10/$parse/lexerr?p0=Unterminated%20quote&p1=s%2013-14%20%5B'%5D&p2=recipe.ID%20!%3D%3D' I am struggling to implement the solution for this error. Any help wou ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

What is the method for adding/removing the 'hidden' attribute within a <p hidden> element

What is the best way to toggle the visibility of 'hidden' in the element <p hidden>My Text</p>? I attempted removing the attribute and setting it to false, but unfortunately, neither method seemed to work. let paragraphElements = d ...

Utilizing JSON data from Google Maps Matrix with JavaScript

I am trying to fetch the real-time duration of a particular route on Google Maps through my JavaScript code. However, I seem to be stuck. Here's what I have written so far: $(document).ready(function Duration() { var d = new Date(); $.ajax({ ...

My Angular directive appears to be missing from the page

Using Electron and AngularJS to implement basic functionality. Currently adding a header and footer that will be displayed on every page. Here is the structure in app.js: 'use strict'; let app = angular.module('marks', ['ngRoute ...

Why is it that the window object in JavaScript lacks this key, while the console has it?

let myFunction = function declareFunc() { console.log(this); // window console.log(this.declareFunc); // undefined console.log(declareFunc); // function body } console.log(this) // window myFunction(); I understand that the this keyword in a functio ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

Two unnamed objects cannot be combined using the AsyncPipe

Currently, I am looking to implement an autocomplete feature using Angular Material in Angular 8. Below is a snippet of the code used in the TypeScript file: @Input() admins: User[]; userGroupOptions: Observable<User[]>; filterFormFG: FormGrou ...

I recently created an application using Vue and I'm exploring options for storing information to use later. Would using js-cookie be a viable solution for this?

After experimenting with Vuex to store user-selected information in my app, I found that the data was lost upon page reload. Switching to Cookies and using js-cookie solved this issue seamlessly. It makes me wonder if there is a downside to relying on cook ...

Is there a way to display the elements of an array in a horizontal layout?

Why is the array contents displayed vertically in the console window rather than horizontally? Is there a method to adjust this formatting? Can you provide guidance on how to show the array elements horizontally instead of vertically using Console.WriteL ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Is there a way to utilize Babel with Webpack while keeping the original folder structure of the source code intact?

I am currently working on a project that has a complex hierarchy as shown below: -src/ -app.js (interacts with server-side code only) -server/ -models/ -routes/ ... -client/ -views/ -scss/ - ...

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

When attempting to retrieve data in a server-side component, Next.js encountered an ECONNREFUSED error with ::1:3000

import React from "react"; import axios from "axios"; interface UsersType { id: string; firstName: string; lastName: string; email: string; } interface dataProps { allUsers: UsersType[]; } async function getData() { try { c ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Ways to customize a bot's status based on the time of day

I'm currently working on enhancing my discord bot by having its status change every hour for a more dynamic user experience. However, I'm facing challenges with JavaScript dates. Can anyone provide some guidance? Below is the snippet of code I ha ...