soupdiver
soupdiver

Reputation: 3673

Sending an "associative array" via POST from AngularJS

I've got an 'filter' object like

{
  name: 'text',
  value: 'xxx',
  field: 'firstname'
}

which represents a filter for a field and is updated when I change values of input fields. I try to store this in an array in the following way:

$scope.active_filters[filter.field] = filter;

So that I know on which field I got which filter. The filtering should happen on server side and so I'm trying to send this array to my API.

$http.post(url, $scope.active_filters)

As I can see in Chrome I've got an array with the desired element in it but length 0

[status: Object]
length: 0
  status: Object
    field: "status"
    name: "text"
    value: "x"
    __proto__: Object
__proto__: Array[0]

But the object is NOT sent in my request. If I add the object via $scope.active_filters.push(filter) it IS sent to the server but it has the index 0 and not my desired value.

How can I achieve both of my targets? A named index in my array and sending the data to the api.

Upvotes: 1

Views: 1772

Answers (1)

Halcyon
Halcyon

Reputation: 57729

I'm guessing here but your code is like this:

var assoc_array = [];
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";

JavaScript doesn't know associative arrays like for instance PHP does. JavaScript has objects, and since everything is an object (even arrays) you can get this situation.

Rather than setting the elements in the array you're assigning properties to the object. This means the magical .length property doesn't get updated because the array is still empty.

If you change you code to:

var assoc_array = {}; // <-- {} instead of []     
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";

You will get an Object (instead of an Array) and you wont have a .length property.

This is how you would use an Array

var indexed_array = [];
indexed_array[0] = "bar";
indexed_array[1] = "lorem";
indexed_array.length; // 2
indexed_array[100] = "foo";
indexed_array.length; // 101 - arrays are never sparse in JS, PHP will give 3
indexed_array[2]; // undefined

Upvotes: 3

Related Questions