How can I verify if there are duplicate items in the cart using Angular 5?

As a newcomer to Angular 5, I am delving into creating a basic shopping cart to master the framework. However, I am currently facing a dilemma regarding how to handle duplicate entries in the cart data. Specifically, I am unsure whether I should store objects in an array or arrays in objects to manage the data efficiently.

This is my current approach in the Home component:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    items: Array<object> = [];
    total_items:Number = 0;
    cart = {};
    broadcast_obj = {items:[],totals:{}};
    total_sum:Number = 0.0;
    htmlToAdd:String = '';

    constructor(private _data: DataService) {  }

    ngOnInit() {
        this._data.cast.subscribe(res => this.broadcast_obj = res);
        this._data.changeCart(this.broadcast_obj);
    }

    additem(id,itemText,amount){
        this.total_items = 10;
        this.total_sum += amount;

        this.cart = {id:id, name: itemText, price: amount,quantity:1};
        if(this.items.length>0){
            this.items.find(x => x.id == 3);//error id does not exist on type object
        }
        this.items.push(this.cart);
        this.broadcast_obj.items = this.items;
        this.broadcast_obj.totals = {total_items:this.total_items,total_sum:this.total_sum};
        console.log(this.broadcast_obj)

    }

}

In my current implementation, I am storing data in two objects and adding them to an array: 1- {id:id, name: itemText, price: amount,quantity:1}; 2- {total_items:this.total_items,total_sum:this.total_sum};

I am now faced with the challenge of checking if an ID already exists in the array and incrementing the quantity. However, my current approach of searching for the ID in the array object is resulting in an error (id does not exist on type object).

Here is the current structure of the array of objects: https://i.sstatic.net/xlxX9.jpg

I have also been contemplating an alternative approach of storing objects in array indexes based on their IDs, such that if an item has an ID of 199, it would be stored in array index[199] for faster retrieval.

I am uncertain which approach would be more efficient in terms of search capability, or if both methods are flawed.

I would appreciate assistance in resolving my error and guidance on structuring the cart data correctly for efficient searching and observable data passing.

Thank you.

Answer №1

The reason for the error is the following line: items: Array<object> = []; This line indicates that items is an array of Objects (javascript objects). Objects do not have properties like id. To resolve this, you should create an interface for your item:

interface ICartItem {
    id: number;
    name: string;
    price: number;
    quantity: number;
}

Then, in your component, you can use items: ICartItem[] = []; (similar to

items: Array<ICartItem> = [];
). This will eliminate the error.

Your component:

// ...
items: ICartItem[] = [];
cart: ICartItem; // no need to initialize it with an empty object
//...

Answer №2

I concur with the answer provided by @BorisLobanov. Additionally, I wanted to share another example demonstrating an alternative approach...

One way to handle this is by declaring items as:

items: Array<any> = new Array<any>();
. This approach can help in addressing potential errors as well.

Nevertheless, as emphasized by @BorisLobanov, and with which I echo agreement, it is important to note that:

Utilizing any is not considered best practice as it undermines the purpose of Typescript


From my perspective, using an array of type any is justified when the "items" are fetched from an API call. This is particularly useful when dealing with arrays of objects containing numerous properties. In such cases, one may only need a few specific properties for processing or when the data itself is not of primary concern, as illustrated below.

The use of any allows you to bypass the strict type checks enforced by the Typescript compiler (no compile-time errors), enabling you to access properties within items in an unsafe manner.


When dealing with nested data structures, the advantage becomes more evident. For example:

australianCities = [
  {
    name: 'Sydney',
    suburbs: [{
      name: 'town 1',
      houses: [{
          population: 3,
          address: 'aa'
        },
        {
          population: 1,
          address: 'bb'
        }
      ]
    }]
  }, ...
];

The thought of defining interfaces for each object within this structure (especially when complexity increases) can be daunting. Moreover, considering the dynamic nature of APIs, it makes more sense to simply calculate the total population across all Australian cities using any.

This process can be simplified using any as demonstrated below:

let sum = (accumulator, currentValue) => accumulator + currentValue;
population = australianCities.map(city => city.suburbs.map(town => town.houses.map(house => house.population).reduce(sum)).reduce(sum)).reduce(sum);

var australianCities = [{
    name: 'Sydney',
    suburbs: [{
      name: 'town 1',
      houses: [{
          population: 3,
          address: 'aa'
        },
        {
          population: 1,
          address: 'bb'
        }
      ]
    }]
  },
  {
    name: 'Perth',
    suburbs: [{
      name: 'town 1',
      houses: [{
          population: 10,
          address: 'aa'
        },
        {
          population: 2,
          address: 'bb'
        }
      ]
    }]
  }
];

var sum = (accumulator, currentValue) => accumulator + currentValue;

totalPopulation = australianCities.map(city => city.suburbs.map(town => town.houses.map(house => house.population).reduce(sum)).reduce(sum)).reduce(sum);

console.log({
  totalPopulation
});

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

Preventing the triggering of events or functions while utilizing angular-gantt

Currently, I am utilizing the Angular directive called angular-gantt to create a gantt chart that displays tasks. Among the various options available, the ones I am focusing on are on-row-clicked, on-task-clicked, and on-task-updated. The issue I am facin ...

What is the best way to attach an event again in jQuery?

My JavaScript/jQuery code initiates a listener to highlight DOM elements when a button is clicked. By clicking the button, the listener event starts (e.g. highlight : function()). If I click on any part of the webpage, the listener stops. However, if I ...

What is the reason behind the label value persistently showing up after the page is refreshed?

Why is the data that I deleted from the database still showing in the label? Even after running the delete function and reloading the page. The label should not have any value once the data is deleted. Here is my code: $(document).on('click', ...

Generating a JSON Array Made up of JSON Elements Using JQuery

Currently, my goal is to send a JSON Object to the backend. Essentially, I aim to retrieve the input from 2 textfields and a list of all selected checkboxes. Below is an excerpt of my JavaScript code: function insertNewHero() { var selectedAbiliti ...

The state variable remains undefined even after integrating useEffect in a React.js component

Hello, I have a component within my React application that looks like this: import React, { useEffect, useState } from "react"; import AsyncSelect from "react-select/async"; import { ColourOption, colourOptions } from "./docs/data"; const App = () => ...

Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS: productApp.directive('notification', function($timeout) { return { restrict : 'E', replace : true, scope : { type: "@", message: "@ ...

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Guide on Capturing Szimek/Signature_Pad using PHP: How to Save Javascript as PHP Variable?

While perusing through StackOverflow, I stumbled upon Szimek/Signature_Pad which allows for the capturing of electronic/digital signatures using Javascript. Even after conducting research, I still find myself puzzled on how to capture the DATA URI into a ...

Manipulate the color of the parent text using a button nested within

I am working on a script that adds a button to div elements with the class name "colors". When the button is clicked, the text color of the parent element will change to a specified color. However, I'm facing an issue where it only changes the last el ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Having trouble finding the correct route using an ajax request

Having trouble finding the correct route through an ajax call In my view, I have 2 HTML buttons that are generated using PHP <?php if ($comment_exist == null): ?> <p><input type ="button" id = "sb" value="I Comment"></p> &l ...

How to Redirect a Webpage to the Same Tab in ASP.NET

I am currently using an asp.net hyperlink control to direct users to a web URL when the hyperlink is clicked. My goal is for the user to open a new tab, rather than a new window, when they click the hyperlink. If the user clicks the link again, I want th ...

Is there a way to identify a visitor's country and automatically direct them to a relevant website?

Despite reading multiple answers, I am still unsure how to redirect my website's visitors based on their country. I have a basic understanding of HTML and JavaScript. Can someone kindly provide me with the code for this task? ...

AngularJS experiencing issues with Bootstrap multiselect functionality

I am currently integrating bootstrap-multiselect into my AngularJS application. To do this, I've included the following scripts in my master page (index.html). <script src="/bower_components/jquery/dist/jquery.min.js"></script> <scrip ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

Disappearing Cloned Form Fields in jQuery

Hey there! I'm trying to duplicate a section of a form using the code below. But for some reason, the copied fields are only visible for a split-second before they disappear. Can anyone spot any errors that might be causing this strange behavior? jQu ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Navigating the complexities of extracting and storing a data type from a collection of objects

Dealing with a messy API that returns inconsistent values is quite challenging. Instead of manually creating types for each entry, I am looking for a way to infer the types programmatically. One approach could be by analyzing an array like this: const arr ...