Search code examples
arraysangulartypescriptangular7angular8

How to convert values of array to array filtered


I have this problem, I use Angular 8, I hope you can help me, I have been unable to solve it for a long time.

I have this array:

datos = [{
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'ADMON',
    Value: '1'
  },
  {
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'ADMON',
    Value: '2'
  },
  {
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'ADMON',
    Value: '3'
  },
  {
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'USER',
    Value: '1'
  },
  {
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'USER',
    Value: '2'
  },
  {
    Description: 'Puede Insertar',
    Id: 1,
    Type: 'USER',
    Value: '4'
  },
]

I need to filter and group them like this :

result = [
  {ADMON: {0: 1, 
           1: 2, 
           2: 3, 
           3: 4}},
  {USER:  {0: 1, 
           1: 2, 
           2: 4}}
];

I've tried many ways but I can't, I hope you can help me, thank you very much in advance.


Solution

  • Here is one potential solutions that use a number of array methods to accomplish the task at hand.

    const datos = [{
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'ADMON',
        Value: '1'
      },
      {
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'ADMON',
        Value: '2'
      },
      {
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'ADMON',
        Value: '3'
      },
      {
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'USER',
        Value: '1'
      },
      {
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'USER',
        Value: '2'
      },
      {
        Description: 'Puede Insertar',
        Id: 1,
        Type: 'USER',
        Value: '4'
      }
    ];
    
    const grouped = datos.reduce((acc, el) => {
      if (!acc[el.Type]) acc[el.Type] = {};
      const index = Object.values(acc[el.Type]).length;
      acc[el.Type] = {
        ...acc[el.Type],
        [index]: el.Value
      }
      return acc;
    }, {});
    
    const final = Object.entries(grouped).map(([key, val]) => {
      return { [key]: val }
    });
    
    console.log(final);