如何在角度2中更改数组结构

时间:2016-10-05 10:35:26

标签: arrays json angular typescript

我的数组就像

    Data=[
    {item:'A',depend:[
                 {dependitem:'B',flag:2},
                 {dependitem:'C',flag:3},
                 {dependitem:'D',flag:2},
                 {dependitem:'E',flag:3}
                     ],group:[2,6]},
    {item:'F',depend:[
                 {dependitem:'G',flag:1},
                 {dependitem:'H',flag:2},
                 {dependitem:'I',flag:1},
                 {dependitem:'J',flag:1}
                     ],group:[1,2]},
          ];

我想将数据阵列更改为

    Group=[
    {group1:[
          {dependitem:'G'},
          {dependitem:'I'},
          {dependitem:'J'}
            ]},
    {group2:[
          {dependitem:'B'},
          {dependitem:'D'},
          {dependitem:'H'}
            ]},
    {group3:[
          {dependitem:'C'},
          {dependitem:'E'}
           ]}
     ];

第二个数组是基于第一个数组上的标志的组,即数据数组。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

PLUNKER

<强>代码:

let groups = {};
this.data.forEach((d) => {
  d.depend.forEach((r) => {
    if(groups['group' + r.flag]) {
      groups['group' + r.flag].push({dependitem: r.dependitem});
    } else {
      groups['group' + r.flag] = [{dependitem: r.dependitem}];
    }
  })
});

Object.keys(groups).forEach((k) => {
  let o = {};
  o[k] = groups[k];
  this.group.push(o)
})

输出这样可以吗?

[
  {
    "group2": [
      {
        "dependitem": "B"
      },
      {
        "dependitem": "D"
      },
      {
        "dependitem": "H"
      }
    ]
  },
  {
    "group3": [
      {
        "dependitem": "C"
      },
      {
        "dependitem": "E"
      }
    ]
  },
  {
    "group1": [
      {
        "dependitem": "G"
      },
      {
        "dependitem": "I"
      },
      {
        "dependitem": "J"
      }
    ]
  }
]