如何使用对象数据在angular2中创建多维数组?

时间:2016-09-06 10:10:19

标签: javascript angularjs arrays multidimensional-array angular

我有对象数组,但我想创建它的数组: 对象格式为:

[
 {"name":"A1","type":"type1"},
 {"name":"A2","type":"type1"},
 {"name":"A3","type":"type1"},
 {"name":"A4","type":"type1"},
 {"name":"B1","type":"type2"},
 {"name":"C1","type":"type3"},
 {"name":"D1","type":"type4"},
 {"name":"D2","type":"type4"}

结果格式为:

["type1"=>[A1,A2,A3,A4],"type2"=>[B1],"type3"=>[C1],"type3"=>[D1,D2]]

2 个答案:

答案 0 :(得分:0)

您可以使用Array#forEach迭代数组,并使用类型为键的对象。

var data = [{ "name": "A1", "type": "type1" }, { "name": "A2", "type": "type1" }, { "name": "A3", "type": "type1" }, { "name": "A4", "type": "type1" }, { "name": "B1", "type": "type2" }, { "name": "C1", "type": "type3" }, { "name": "D1", "type": "type4" }, { "name": "D2", "type": "type4" }],
    grouped = {};

data.forEach(function (a) {
    grouped[a.type] = grouped[a.type] || [];
    grouped[a.type].push(a.name);
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您也可以使用reduce

执行此操作
.reduce((prev, cur) => {
  if (prev.hasOwnProperty(cur.type))
    prev[cur.type].push(cur.name);
  else
    prev[cur.type] = [cur.name];

  return prev;
}, {});

这种方法的好处是不需要额外的变量超出reduce的范围,它只是返回你的分组对象。

请参阅fiddle