gpt4 book ai didi

javascript - Angular - 仅在唯一时推送到数组

转载 作者:数据小太阳 更新时间:2023-10-29 05:50:00 24 4
gpt4 key购买 nike

我有一个 Angular 应用程序可以收集发票项目的值(value),我想确保只有唯一的项目被添加到这个集合中,但我没有运气。

我正在向这个集合推送 3 条信息:id、price 和 type。我想确保当前集合中没有与这 3 点匹配的内容。

// My container
$scope.invoice = {
items: [{
}]
}


$scope.addPhoto = function() {
console.log('Withdrawing Photo: '+ $scope.item.id);
if ($scope.invoice.items.indexOf(item.id) != $scope.item.id)
{
$scope.invoice.items.push({
id: $scope.item.id,
price: $scope.item.price,
type: 'photo'
});
}
}

//尽量避免这样的集合

发票:{项目:[ { } , {编号:25价格: 0类型:照片 } , {编号:25价格: 0类型:照片 } ] }

enter image description here

最佳答案

.filter正是您所需要的。

$scope.addPhoto = function() {
console.log('Withdrawing Photo: '+ $scope.item.id);
var matches = $scope.invoice.items.filter(function(datum) {
return datum.id === $scope.item.id &&
datum.price === $scope.item.price &&
datum.type === $scope.item.type;
});
if (!matches.length)
{
$scope.invoice.items.push({
id: $scope.item.id,
price: $scope.item.price,
type: 'photo'
});
}
}

Semi-contrived JSFiddle

关于javascript - Angular - 仅在唯一时推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22719340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com