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.