[英]How to add the new value and update the existing value in array of objects on button click in angularjs?
I am inserting the object values in the array on button click, I want to update the value of those objects if objects are already present in the array on same button click. 我在单击按钮时将对象值插入数组中,如果在单击按钮时数组中已经存在对象,我想更新那些对象的值。 How can I do that ? 我怎样才能做到这一点 ? I am adding the values in the array using push function which is as follows: 我正在使用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]);
}
}
Please see this code considering that if any key matched edit that record - 考虑到是否有键匹配,请查看此代码以编辑该记录-
$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.