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:
$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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.