从对象数组创建多级组

时间:2014-03-04 07:54:42

标签: javascript underscore.js grouping

我有以下类型的数据

data = [{
    "grp" : ["A", "B", "C"],
    "val" : [1, 2, 3]
  }, {
    "grp" : ["A", "B", "D"],
    "val" : [2, 3, 4]
  }, {
    "grp" : ["A", "C", "C"],
    "val" : [1, 3, 5]
  }, {
    "grp" : ["B", "Y", "E"],
    "val" : [1, 3, 2]
  }
]

我想制作像这样的团体

groups = {
  "A": {
    "B": {
      "C": [
        [1, 2, 3],
        [2, 3, 4]
      ],
      "D": [
        [1, 2, 3],
        [2, 3, 4]
      ]
    },
    "C": {
      "C": [
        [1, 3, 5]
      ]
    }
  },
  "B": {
    "Y": {
      "E": [
        [1, 3, 2]
      ]
    }
  }
}

grp数组最多可包含3个元素。

我尝试使用下面的下划线,但是,我最终创建了单独的组,而不是嵌套组。

var groups = _(data).reduce(function(memo, o) {
    _(o.groups).each(function(j) {
        memo[j] = memo[j] || [ ];
        memo[j].push(o);
    });
    return memo;
}, { });

欣赏正确方向的任何想法。

2 个答案:

答案 0 :(得分:1)

var out = {};
_.each(data,function(item)
       {
           var firstKey = item['grp'][0];
           var secondKey = item['grp'][1];
           out[firstKey] = out[firstKey] || {};
           out[firstKey][secondKey] = out[firstKey][secondKey] || [];
           out[firstKey][secondKey].push(item['val']);
       });

<强>演示http://jsfiddle.net/HJngC/2/

答案 1 :(得分:1)

试试这个:

var data = [{
    "grp": ["A", "B"],
    "val": [1, 2, 3]
}, {
    "grp": ["A", "B"],
    "val": [2, 3, 4]
}, {
    "grp": ["A", "C"],
    "val": [1, 3, 5]
}, {
    "grp": ["B", "Y"],
    "val": [1, 3, 2]
}]

// create an object to hold the revised structured data
var newData = {};
_.map(data, function (obj, key) {
    // check whether object is present or not
    if (_.isUndefined(newData[obj.grp[0]])) { //if object is undefined
        newData[obj.grp[0]] = {};
        newData[obj.grp[0]][obj.grp[1]] = [obj.val]; // add an array to second child of grp
    } else { // if object already exists
        // check whether second child of grp is present
        if (_.isUndefined(newData[obj.grp[0]][obj.grp[1]])) { // if not present - create an associated array
            newData[obj.grp[0]][obj.grp[1]] = [obj.val];
        } else { // if present - add value to it
            newData[obj.grp[0]][obj.grp[1]].push(obj.val);
        }
    }
});

// print on console window
console.log(newData);

JSFiddle链接:http://jsfiddle.net/4G57E/