简体   繁体   English

我想避免 id 重复并使用 push 添加值

[英]I want to avoid id duplication and add values using push

controller控制器
$scope.items = [ $scope.items = [
{"id" : 1 , "itemname" : "name_1", "comment" : "dsdsd", "price" : 5000}, {"id" : 1 , "itemname" : "name_1", "comment" : "dsdsd", "price" : 5000},
{"id" : 1 , "itemname" : "name_2", "comment" : "dddd", "price": 3000}, {"id": 1, "itemname": "name_2", "comment": "dddd", "price": 3000},
{"id" : 3 , "itemname" : "name_3", "comment" : "sdasd", "price" : 2000}, {"id" : 3 , "itemname" : "name_3", "comment" : "sdasd", "price" : 2000},
{"id" : 4 , "itemname" : "name_4", "comment" : "asdasd", "price" : 3000}, {"id" : 4 , "itemname" : "name_4", "comment" : "asdasd", "price" : 3000},
{"id" : 5 , "itemname" : "name_5", "comment" : "asdasd", "price" : 2000} {"id" : 5 , "itemname" : "name_5", "comment" : "asdasd", "price" : 2000}
] ]

$scope.addToCart=function(item){ $scope.addToCart=function(item){
cart.add(item);购物车。添加(项目);
} }

service服务
cartObj.cart.add=function(item){ carObj.cart.add=function(item){
cartObj.cart.push(item); carObj.cart.push(item);
}; };

<div ng-repeat="item in cart">
<div>id: {{item.id}}</div>
<div>itemname: {{item.itemname}}</div>
</div>

top code cart.html顶部代码cart.html

<div ng-repeat="item in items">
<a ng-click="addToCart(item)">[ addcart ]</a>
</div>

top code index.html顶部代码 index.html

Example OUTPUT示例输出
id 1编号 1
name_1 5000名称_1 5000
name_2 3000 name_2 3000
id 3编号 3
name_3 2000 name_3 2000
id 4编号 4
name_4 3000 name_4 3000
id 5编号 5
name_5 2000 name_5 2000

You can check if it's safe to push to an array before pushing on to it.在推送到数组之前,您可以检查推送到数组是否安全。

if ($scope.items.indexOf(item) == -1) {
   $scope.items.push(item);
}

You can check wether there's already an item with that id, before pushing.在推送之前,您可以检查是否已经存在具有该 ID 的项目。

let oldItem = $scope.items.find(elm => elm.id === item.id);
if(oldItem){
    //you can assign the properties of `item` to the one in the list
    Object.assign(oldItem, item);
}else{
    $scope.items.push(item);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM