将相同的“类别"对象分组 [英] Group the same `category` objects

查看:47
本文介绍了将相同的“类别"对象分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对以下来源的原始数据进行分组:

I'm trying to group the raw data from:

items:
[
    {
        category: "blog",
        id      : "586ba9f3a36b129f1336ed38",
        content : "foo, bar!"
    },
    {
        category: "blog",
        id      : "586ba9f3a36b129f1336ed3c",
        content : "hello, world!"
    },
    {
        category: "music",
        id      : "586ba9a6dfjb129f1332ldab",
        content : "wow, shamwow!"
    },
]

[
    {
        category: "blog",
        items:
        [
            {
                id      : "586ba9f3a36b129f1336ed38",
                content : "foo, bar!"
            },
            {
                id      : "586ba9f3a36b129f1336ed3c",
                content : "hello, world!"
            },
        ]
    },
    {
        category: "music",
        items:
        [
            {
                id      : "586ba9a6dfjb129f1332ldab",
                content : "wow, shamwow!"
            }
        ]
    }
]

像这样的格式可以帮助我在前端一起打印相同的类别数据.

The format like this helps me to print the same category data together in the frontend.

category 字段的内容是动态的,因此不确定如何将其存储到临时对象并对其进行排序?

The content of the category field is dynamically, so I'm not sure how do I store it to a temporary object and sort them, any thoughts?

(我想这个问题的标题更好,如果标题更好,请进行编辑.)

推荐答案

您可以使用 Array#reduce 一次完成该操作:

You can do it using Array#reduce in one pass:

var items = [{"category":"blog","id":"586ba9f3a36b129f1336ed38","content":"foo, bar!"},{"category":"blog","id":"586ba9f3a36b129f1336ed3c","content":"hello, world!"},{"category":"music","id":"586ba9a6dfjb129f1332ldab","content":"wow, shamwow!"}];

var result = items.reduce(function(r, item) {
  var current = r.hash[item.category];
  
  if(!current) {
    current = r.hash[item.category] = { 
      category: item.category,
      items: []
    };
    
    r.arr.push(current);
  }

  current.items.push({
    id: item.id,
    content: item.content
  });
  
  return r;
}, { hash: {}, arr: [] }).arr;
  
console.log(result);

或者使用 Map 的ES6方式:

Or the ES6 way using Map:

const items = [{"category":"blog","id":"586ba9f3a36b129f1336ed38","content":"foo, bar!"},{"category":"blog","id":"586ba9f3a36b129f1336ed3c","content":"hello, world!"},{"category":"music","id":"586ba9a6dfjb129f1332ldab","content":"wow, shamwow!"}];

const result = [...items.reduce((r, { category, id, content }) => {
  r.has(category) || r.set(category, {
    category,
    items: []
  });
  
  r.get(category).items.push({ id, content });
  
  return r;
}, new Map).values()];
  
console.log(result);

这篇关于将相同的“类别"对象分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆