Javascript 如何在第5节中检查购物车中的重复项目?

Javascript 如何在第5节中检查购物车中的重复项目?,javascript,jquery,angular,typescript,Javascript,Jquery,Angular,Typescript,我是angular 5的新手,我正在制作一个简单的购物车来学习angular 5。我陷入了一个困惑的境地,我不知道如何检查购物车数据中的重复条目。事实上,问题是我不知道应该将对象存储在数组中还是将数组存储在对象中以存储数据 这就是我正在做的 主分量 import { Component, OnInit } from '@angular/core'; import { DataService } from '../data.service'; @Component({ selector: 'a

我是angular 5的新手,我正在制作一个简单的购物车来学习angular 5。我陷入了一个困惑的境地,我不知道如何检查购物车数据中的重复条目。事实上,问题是我不知道应该将对象存储在数组中还是将数组存储在对象中以存储数据

这就是我正在做的 主分量

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.items_count = this.cart.length;
        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)
        //this._data.changeCart(this.broadcast_obj);
    }

}
从'@angular/core'导入{Component,OnInit};
从“../data.service”导入{DataService};
@组成部分({
选择器:“应用程序主页”,
templateUrl:“./home.component.html”,
样式URL:['./home.component.scss']
})
导出类HomeComponent实现OnInit{
项目:数组=[];
项目总数:数量=0;
cart={};
广播对象={项目:[],总数:{};
总和:数字=0.0;
htmlToAdd:String='';
构造函数(私有_数据:数据服务){}
恩戈尼尼特(){
//this.items\u count=this.cart.length;
this.\u data.cast.subscribe(res=>this.broadcast\u obj=res);
this.\u data.changeCart(this.broadcast\u obj);
}
additem(id、itemText、amount){
本表所列项目总数=10;
此项。总额+=金额;
this.cart={id:id,name:itemText,price:amount,quantity:1};
如果(此.items.length>0){
this.items.find(x=>x.id==3);//类型对象上不存在错误id
}
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)
//this.\u data.changeCart(this.broadcast\u obj);
}
}
我将数据存储在两个对象中,并将它们放入数组中 1-{id:id,name:itemText,price:amount,quantity:1}; 2-{total_items:this.total_items,total_sum:this.total_sum}

现在我想检查id是否存在,然后增加数量,但我不知道我做得对吗,因为我正在数组对象中搜索id,它显示错误,如注释中所示(类型对象上不存在id)

以下是对象数组的当前结构

我还想,如果我将对象存储在其ID的数组索引中 如果item id=199,那么我将对象存储在数组索引[199]中,以便快速搜索数组中的任何项

我仍然不知道哪种方法更好,因为从搜索的角度来看,或者两者都是错误的

请解决我的错误,并帮助我以正确的结构存储购物车数据,以便我可以快速搜索项目,并以可观察的方式传递购物车数据


谢谢。

由于这一行,您将收到错误:
items:Array=[]
这一行表示
是一个对象数组(javascript对象)。对象没有id之类的属性。您需要为项目创建一个接口:

interface ICartItem {
    id: number;
    name: string;
    price: number;
    quantity: number;
}
然后在组件中可以执行
项:iCarItem[]=[](与
项相同:数组=[];
)这将使错误消失

您的组件:

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

我同意BorisLobanov接受的答案,我只是想再举一个例子,说明你还可以如何做到这一点

通过将
items
定义为:
items:Array=newarray()您还将减轻这些错误

但是,正如我同意的BorisLobanov所述,请注意:

使用any不是一个很好的实践,它使Typescript变得毫无意义


。。。在我看来,使用类型为
any
的数组的一个地方是从API调用派生“项”时。原因是您可能会收到一个包含100个属性的对象数组。但是,您只希望使用4个属性。。。或者对于下面显示的示例,您需要数据达到某个值,但实际上并不关心数据本身

使用
any
可防止typescript编译器(编译时无错误)验证
项的类型结构,从而允许您
不安全地访问已知存在的属性


当数据结构具有嵌套对象时,其好处显而易见,例如:

australianCities = [
  {
    name: 'Sydney',
    suburbs: [{
      name: 'town 1',
      houses: [{
          population: 3,
          address: 'aa'
        },
        {
          population: 1,
          address: 'bb'
        }
      ]
    }]
  }, ...
];
想到为这里的每个对象定义所有这些接口(想象一个实际上很复杂的接口),我的灵魂已经受到了伤害,特别是当API可以改变时,如果我想做的就是把澳大利亚所有城市的总人口加起来的话

但是,通过使用
any
,这可以大大减少麻烦。。。比如:

let sum = (accumulator, currentValue) => accumulator + currentValue;
population = australianCities.map(city => city.towns.map(town => town.houses.map(house => house.population).reduce(sum)).reduce(sum)).reduce(sum);
var澳大利亚=[{
姓名:'悉尼',
郊区:[{
名称:'town 1',
房屋:[{
人口:3,
地址:'aa'
},
{
人口:1,
地址:'bb'
}
]
}]
},
{
名称:“珀斯”,
郊区:[{
名称:'town 1',
房屋:[{
人口:10,
地址:'aa'
},
{
人口:2,
地址:'bb'
}
]
}]
}
];
var总和=(累加器,currentValue)=>累加器+currentValue;
totalPopulation=australiancies.map(城市=>城市.郊区.map(城镇=>城镇.房屋.map(房屋=>房屋.人口).reduce(总和)).reduce(总和)).reduce(总和);
console.log({
总人口

});
或只运行
项:Array=newarray()@BorisLobanov谢谢你的回答。我应该把接口放在哪里,因为当我把它放在组件中时,整个类都充满了错误。你可以把它放在一个单独的文件中并导入(只需在声明接口之前添加
export
),或者把它放在类的上面或下面/component@BorisLobanov现在这行是红色的this.items.push(this.cart);错误:{}类型的参数不可分配给类型icartItem@BorisLobanov我还编写了您的代码项:Array=[];但仍然存在错误。