AngularJS toArray Filter
Although AngularJS 1.x supports iterating over an object (keys and values), it is
not the preferred way of doing things. Moreover, filters like
just don't work with objects; they are designed to work with arrays.
This filter can convert your objects into stable arrays that can then be filtered and sorted using the standard AngularJS filters.
The easiest way to install is using bower:
Alternatively you can download from the GitHub project: https://github.com/petebacondarwin/angular-toArrayFilter
toArrayFilter.js file into your web app after loading
Make sure that your AngularJS application references the
Now if you have an object that you wish to repeat over, just slip the
toArray filter in
before you try sorting or filtering:
How it works
The filter iterates over the object's keys and creates an array containing the value of each
property. By default, the filter also attaches a new property
$key to the value containing
the original key that was used in the object we are iterating over to reference the property.
Not adding the
If you don't want the
$key property to be attached to each of the property values, you simply
put an additional parameter on the
filter has its own set of things to be aware of when using it:
- It only works with plain Objects - don't try to filter arrays and strings with it.
- If you don't disable it, the filter will modify each property value with a new
- If the object you are iterating over contains values that are not objects then you must disable
$keyproperty or it will error - non-objects cannot have properties attached to them.
- This filter is not compatible with IE8. (It uses
Object.definePropertywhich don't work well or at all in Internet Explorer 8 (IE8).
Here is a fuller example of using the
toArray filter on an object, to allow sorting and filtering
date property on each property of the original object. It also demonstrates how you can easily
update the original object and the array will stay in sync.
Check out the Live Demo