I have this array of objects, and I want them to group by their specific key, in this case tags
var items = [
{id: 0, tags: ["a"], name: "foo"},
{id: 1, tags: [], name: "bar"},
{id: 2, tags: ["a"], name: "bazz"},
{id: 3, tags: ["b"], name: "wah"},
{id: 4, tags: ["c"], name: "ikr"},
{id: 5, tags: ["a"], name: "wtf"},
{id: 6, tags: ["a","b"], name: "gtg"},
{id: 7, tags: ["c"], name: "afk"}
]
And so I used underscore, like so:
var groupItems = _.groupBy(items, function(obj) {
return obj.tags;
});
The problem with that is that:
{
"a": [
{"id": 0,"tags": ["a"],"name": "foo"},
{"id": 2,"tags": ["a"],"name": "bazz"},
{"id": 5,"tags": ["a"],"name": "wtf"}
],
"": [
{"id": 1,"tags": [],"name": "bar"}
],
"b": [
{"id": 3,"tags": ["b"],"name": "wah"}
],
"c": [
{"id": 4,"tags": ["c"],"name": "ikr"},
{"id": 7,"tags": ["c"],"name": "afk"}
],
"a,b": [
{"id": 6,"tags": ["a","b"],"name": "gtg"}
]
}
If you would also notice, those who has multiple tags, created a joined key from the array tags which is quite an undesirable result. How can I, group them by tags and duplicate the data when they have multiple tags
id:6in result have"tags": ["a","b"]but in sourcetags: ["a"]