【问题标题】:Group the same `category` objects [duplicate]将相同的“类别”对象分组[重复]
【发布时间】:2017-05-25 14:29:31
【问题描述】:

我正在尝试将原始数据分组:

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!"
            }
        ]
    }
]

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

category 字段的内容是动态的,所以我不确定如何将其存储到临时对象并对其进行排序,有什么想法吗?

(我想不出更好的问题标题,如果你有更好的标题,请编辑。)

【问题讨论】:

标签: javascript arrays object multidimensional-array categorization


【解决方案1】:

您可以使用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);

【讨论】:

  • 诅咒你的一通:p(不错)
【解决方案2】:

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

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

babel 转换成哪个

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

【讨论】:

    【解决方案3】:

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

    // Items
    // var items = []
    
    // Create an empty object, used to store the different categories.
    var temporaryObject = {}
    
    // Scan for each of the objects in the `items` array.
    items.forEach((item) =>
    {
        // Create a category in the teporary object if the category
        // hasn't been created.
        if(typeof temporaryObject[item.category] === "undefined")
            temporaryObject[item.category] = []
    
        // Push the item to the its category of the `temporaryObject`.
        temporaryObject[item.category].push({
            id     : item.id,
            content: item.content
        })
    })
    
    
    // Create a empty array used to stores the sorted, grouped items.
    var newItems = []
    
    // Scan for each of the category in the `temporaryObject`
    for(var category in temporaryObject)
    {
        // Push the new category in the `newItems` array.
        newItems.push({
            category: category,
            items   : []
        })
    
        // Get the last category index of the `newItems` array,
        // so we can push the related data to the related category.
        var lastItem = newItems.length - 1
    
        // Scan for the related category in the `temporaryObject` object.
        temporaryObject[category].forEach((item) =>
        {
            // Push the related data to the related category of the `newItems` array.
            newItems[lastItem].items.push(item)
        })
    }
    
    // Prints the sorted, grouped result.
    console.log(newItems) 
    

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 1970-01-01
      • 2014-06-18
      • 2015-10-11
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2012-06-27
      相关资源
      最近更新 更多