[英]How to add the new value and update the existing value in array of objects on button click in angularjs?
我在單擊按鈕時將對象值插入數組中,如果在單擊按鈕時數組中已經存在對象,我想更新那些對象的值。 我怎樣才能做到這一點 ? 我正在使用push函數添加數組中的值,如下所示:
$scope.demoarray = [];
$scope.demoarray.push({
sample key1: $scope.demovalue1,
sample key2: $scope.demovalue2
});
$scope.demoarray = [];
$scope.demoarray.push({
sample key1: $scope.demovalue1,
sample key2: $scope.demovalue2
});
if($scope.demoarray.length>0){
//if there is elements of array
//reset the array
//$scope.demoarray = [];
//or push
//$scope.demoarray.push({...});
//or update item by index
//$scope.demoarray[1] = {"newKey","newValue"}
}
if($scope.demoarray[0]["sample key1"]){
//if there is value of key exists in the first item of array
//$scope.demoarray.push({...});
//or
//$scope.demoarray[0] = {};
//or
//delete $scope.demoarray[0]["sample key1"];
//$scope.demoarray.splice(0,1);
//$scope.demoarray[1]["sample key1"]//key of 2nd item
//$scope.demoarray[2]["sample key1"]//key of 3nd
}
if($scope.demoarray[0]["sample key1"]=="specific"){
//take any action
}
//and you can loop over all items using for
for(var i=0;i<$scope.demoarray.length;i++){
//use any if statements above working with i as index
for(var k in $scope.demoarray[i]){
console.log(k +" : "+ $scope.demoarray[i][k]);
}
}
考慮到是否有鍵匹配,請查看此代碼以編輯該記錄-
$scope.demoarray = [];
var index1=-1;
var index2=-1;
var recordToBeAdded:{
key1: $scope.demovalue1,
key2: $scope.demovalue2};
if($scope.demoarray.lenght>0){
index1 = $scope.demoarray.findIndex(x=>x.key1===recordToBeAdded.key1) //find index of 1st key
index2 = $scope.demoarray.findIndex(x=>x.key1===recordToBeAdded.key2) // find index of 2nd key
}
if(index1==-1 && index2==-1) // add if record is new
{
$scope.demoarray.push(recordToBeAdded);
}
else if(index1!==-1) // add edit same record if found 1st key matched
{
$scope.demoarray[index1] = recordToBeAdded
}
else{ // edit record if 2nd key matched
$scope.demoarray[index2] = recordToBeAdded
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.