sainu sainu - 2 months ago 6
TypeScript Question

How to change Array structure in angular 2

My Array is like

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


I want to change Data Array to

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


The second array is group on the basis of flag on the first array ie Data array.
Thanks in advance.

Answer

PLUNKER

Code:

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

Output: is this OK ?

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