按键排序JavaScript对象

时间:2017-08-27 21:59:41

标签: javascript

我有一组具有以下格式的对象:

{
  {
    "articleId": "a0sf1000004najmAAA",
    "articleName": "A value for name",
    "footnote": "",
    "mainCat": "A Category 1",
    "subCat": "A SubCategory 1",
  }, {
    "articleId": "a0sf1000004najmAAA",
    "articleName": "A value for name",
    "footnote": "",
    "mainCat": "A Category 1",
    "subCat": "A SubCategory 2",
  },
}

在缩减和分组后,我希望得到以下内容:

{
  "A Category 1": {
    "A SubCategory 1": {
      {
        some items belonging to SubCat 1 and Cat 1
      }
    },
    "A SubCategory 2": {
      {
        some items belonging to SubCat 2 and Cat 1
      }
    }
  }
}

现在,我可以返回按子类别分组的所有单篇文章,但如何按主要类别对子类别进行分组?

var catalog = data;

var groupBySubCat = catalog.reduce(function(obj, item) {
  obj[item.subCat] = obj[item.subCat] || [];
  obj[item.subCat].push(item);
  return obj;
}, {});

var groups = Object.keys(groupBySubCat).map(function(key) {
  return {
    subCat: key,
    tests: groupBySubCat[key]
  };
});

var maingroups = Object.keys(groupBySubCat).map(function(key) {
  return {
    subCat: key,
    tests: groupBySubCat[key]
  };
});

任何改进都将受到赞赏。

1 个答案:

答案 0 :(得分:2)

此功能应该可以胜任。

function getGroupedByCategory(list){
    var ret = {}
    for(var i=0;i<list.length;i++){
        var mainCat = list[i].mainCat
        var subCat = list[i].subCat

        if(!ret[mainCat]) // check if mainCat key exists
            ret[mainCat] = {} // if not create new object

        if(!ret[mainCat][subCat]) // check if subCat exists in mainCat object
            ret[mainCat][subCat] = [] // if not create new list

        ret[mainCat][subCat].push(list[i]) // push current element in the designated list
    }
    return ret
}