1

I have several checkboxes that you can click on. For every checkbox you click on, an ID, that is connected to the checkbox, is pushed into an array:

HTML:

<tr ng-repeat="info in test">
  <td>{{info.stracka}}</td><td>{{info.tid}}</td>
  <td><input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa(info.id)">
</tr>

Controller:

$scope.testa = function(id) {   //När vi klickar i de olika checkboxarna, så fyllas arrayen med dessa
        $scope.checkboxes.push(id);
        console.log($scope.checkboxes);
    };

After this, I'm supposed to send this array containing the ID's to my backend. However, I want to send this Id's in an Object, instead of an array. How can I "push" data, like I do above, into and Object?

Michael
  • 3,308
  • 5
  • 24
  • 36
user500468
  • 1,183
  • 6
  • 21
  • 36

3 Answers3

1

You can't push data into object. Consider object as an collection of key value pair. For every value you want to store into object, you need a key. That's why I was asking about your server side object.

So, in your case, before storing data into an object, i need a key. So, I have to do this like this

var testa = function(id){
     checkbox[id]=id;
}

This code would definitely store your keys in the object, but look at this.

Object {5: 5, 6: 6} 

This is really how the values are stored.

If you use array instead, your working would be simplified a lot on server side.

Gaurav
  • 3,614
  • 3
  • 30
  • 51
0

I am not sure why you need that but one possible solution is Add name to your checkbox

<input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa(info.id, 'UNIQUE_NAME')">

init check boxes to object

    $scope.checkboxes = {};

then modify you function

$scope.testa = function(id, name) {  
        $scope.checkboxes[name] = id;
        console.log($scope.checkboxes);
    };
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
0

While not exactly answering your question about "pushing" - since you cannot push to an object, you could convert your array to object just before sending it using this.

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] !== undefined) rv[i] = arr[i];
  return rv;
}

In your example, you would do something like

$scope.checkboxesObject = toObject($scope.checkboxes);

and then send this new $scope.checkboxesObject.

However, make sure you really are "supposed" to send this to backend as an object.

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82