按键分组对象数组 [英] Grouping an array of objects by key
问题描述
我有这个对象数组,我希望它们按它们的特定键分组,在这种情况下,是标签
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;
});
问题在于:
{
"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"}
]
}
如果您还注意到,那些具有多个标签的人从数组<中创建了 joined
键。 code>标签,这是非常不理想的结果。如何将它们按标记
分组并在它们具有多个标记
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
推荐答案
假定当项目具有多个标签 _。groupBy
时,您希望每个标签下都有重复的条目
Assuming you want duplicate entries under each tag when an item has multiple tags _.groupBy
will not do what you want as it simply splits a collection up (won't duplicate entries).
相反,您将需要手动遍历项目,然后遍历每个项目的标签并为您建立列表(如果需要,可以使用 _。each
):
Instead, you will need to loop over your items manually, then each item's tags and build up your list for you (you could use _.each
if you wanted):
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"}
];
var groupItems = {};
for (var i = 0, item; item = items[i]; i++) {
for (var t = 0, tag; tag = item.tags[t]; t++) {
// If we do not have an array for our tag, add one
groupItems[tag] = groupItems[tag] || [];
// Push out item onto the tag's list in our groupItems
groupItems[tag].push(item);
}
}
哪个会给您:
{
"a": [
{"id": 0,"tags": ["a"],"name": "foo"},
{"id": 2,"tags": ["a"],"name": "bazz"},
{"id": 5,"tags": ["a"],"name": "wtf"},
{"id": 6,"tags": ["a","b"],"name": "gtg"}
],
"b": [
{"id": 3,"tags": ["b"],"name": "wah"},
{"id": 6,"tags": ["a","b"],"name": "gtg"}
],
"c": [
{"id": 4,"tags": ["c"],"name": "ikr"},
{"id": 7,"tags": ["c"],"name": "afk"}
]
}
这篇关于按键分组对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!