1

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks man! Using an object instead an array fixed the problem. And yeah I know that javascript has object an no associative arrays that's why I put it between inside " :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.