将相同的`category`对象分组

时间:2017-01-10 23:06:32

标签: javascript arrays object multidimensional-array categorization

我试图将原始数据分组:

ng-if="isAuthenticated()"

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!" } ] } ] 字段的内容是动态的,所以我不确定如何将它存储到临时对象并对它们进行排序,任何想法?

(我无法为这个问题考虑更好的标题,如果你有更好的标题,请编辑。)

3 个答案:

答案 0 :(得分:3)

您可以一次使用Array#reduce执行此操作:

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方式:

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);

答案 1 :(得分:1)

就个人而言,没有任何帮助库,我只会这样做

var step1 = items.reduce((result, {category, id, content}) => {
    result[category] = result[category] || [];
    result[category].push({id, content});
    return result;
}, {});
var result = Object.keys(step1).map(category => ({category, items: step1[category]}));

哪个巴贝尔转换为

var step1 = items.reduce(function (result, _ref) {
    var category = _ref.category,
        id = _ref.id,
        content = _ref.content;

    result[category] = result[category] || [];
    result[category].push({ id: id, content: content });
    return result;
}, {});
var result = Object.keys(step1).map(function (category) {
    return { category: category, items: step1[category] };
});

答案 2 :(得分:0)

所以我刚用以下代码(jsfiddle)解决了这个问题:

category