如何在angularjs中点击按钮时添加新值并更新对象数组中的现有值?

时间:2016-10-21 08:50:29

标签: javascript jquery angularjs arrays

我在按钮单击时在数组中插入对象值,如果对象在相同的按钮单击中已存在于数组中,我想更新这些对象的值。我怎样才能做到这一点 ? 我使用push函数在数组中添加值,如下所示:

$scope.demoarray = [];

$scope.demoarray.push({                     
                        sample key1: $scope.demovalue1,
                        sample key2: $scope.demovalue2     
                       });

2 个答案:

答案 0 :(得分:0)

    $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]);
   }
   }

答案 1 :(得分:0)

请参阅此代码,考虑到如果任何密钥匹配编辑记录 -

$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
    }