I have the following object that I'm receiving from an API:
{
'2012-12-12': [
{ 'id': 1234,
'type': 'A' },
{ 'id': 1235,
'type': 'A' },
{ 'id': 1236,
'type': 'B' },
],
'2012-12-13': [
{ 'id': 1237,
'type': 'A' },
{ 'id': 1238,
'type': 'C' },
{ 'id': 1239,
'type': 'B' },
]
}
Then I want to have another variable named types
of type Array
that will hold every possible value of the type
attribute of each one of the objects. In this case it would be:
types = ['A', 'B', 'C']
I'm trying to have it done in a functional way (I'm using underscore.js) but I'm unable to figure out a way of doing it. Right now I'm using
types = [];
_.each(response, function(arr1, key1) {
_.each(arr1, function(arr2, key2) {
types.push(arr2.type);
});
});
types = _.uniq(types);
But that's very ugly. Can you help me in figuring out a better way of writing this code?
Thanks!
If you just want shorter code, you could flatten the objects into a single Array, then map that Array.
Here's another version. Mostly just for curiosity's sake.
Here's another one.
And another.
This should work:
Fiddle: http://jsfiddle.net/NFSfs/
Of course, you can remove all whitespace if you want to:
or without chaining:
flatten seems to work on objects, even though the documentation clearly states it shouldn't. If you wish to code against implementation, you can leave out the call to
values
, but I don't recommend that. The implementation could change one day, leaving your code mysteriously broken.