I found myself in the situation where my database required an array of acceptable values, but my UI was using angular checkboxes requiring an object model. I wanted to be able to persist my model as an array, but bind it to my elements as a single object with boolean properties. (think ‘Check all that apply‘ options)
['Red','Green','Blue'] vs. { 'Red': true, 'Green': true, 'Blue': true }
Underscore provides some great helper functions that make these conversions only 1 line of code. _.reduce will boil down a list of values to one single value. Exactly what I needed to convert from the list to the object.
Seed it with an empty object and create a key/value pair for each element in the array.
_.reduce(['a','b','c'], function (memo, val) { memo[val] = true; return memo; }, {});
>>> {a: true, b: true, c: true}
I then bind this new object to my angular checkboxes.
The Trick: If the user turns ON and then OFF the checkbox, angular will add a key/value pair to the array with false. those must be removed before converting back!
_.pick will let me iterate through the elements in the object and return only the keys that pass the test. _.keys will then turn that object back into an array!
>>> var obj = {Blue: true, Green: true, Red: true, Yellow: false, Purple: false}
_.pick(obj, function (value, key, object) { return value == true; });
>>> {Blue: true, Green: true, Red: true}
_.keys(_.pick(obj, function (value, key, object) { return value == true; }));
>> ['Blue','Green','Red']
So using _.reduce, _.pick, and _.keys I am able to easily convert between the array and the object.
Cheers!