2

I have an array of objects

[
{
 job_code: '123',
 application: 'Tree',
 permission_name: 'AP_SEARCH'
},
{
 job_code: '123',
 application: 'Dog',
 permission_name: 'ALL_FA_SEARCH'
},
{
 job_code: '123',
 application: 'Tree',
 permission_name: 'AP_DOWNLOAD'
}
]

And I need the format like

[
{ name: 'Tree', permissions: ['AP_SEARCH', AP_DOWNLOAD'] },
{ name: 'Dog', permissions: 'ALL_FA_SEARCH' },
]

My code is

const allowedApplications = rdsData.map((key) => ({ name: key.application, 
permissions: key.permission_name }));
console.log(rdsData);

But it Output like below

[
{ name: 'Tree', permissions: 'AP_SEARCH' },
{ name: 'Dog', permissions: 'ALL_FA_SEARCH' },
{ name: 'Tree', permissions: 'AP_DOWNLOAD' }
]

Please Help. Thanks for your time

ahkam
  • 607
  • 7
  • 24

1 Answers1

3

You could group by application by using an object.

const
    data = [{ job_code: '123', application: 'Tree', permission_name: 'AP_SEARCH' }, { job_code: '123', application: 'Dog', permission_name: 'ALL_FA_SEARCH' }, { job_code: '123', application: 'Tree', permission_name: 'AP_DOWNLOAD' }],
    result = Object.values(data.reduce((r, { application: name, permission_name }) => {
        r[name] ??= { name, permissions: [] };
        r[name].permissions.push(permission_name);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • [ { application: 'Tree', permission_name: [ 'AP_SEARCH', 'AP_DOWNLOAD' ] }, { application: 'Dog', permission_name: 'ALL_FA_SEARCH' } ] This is the result of yours. But need 'All_FA_SEARCH' also inside an array – ahkam Mar 16 '21 at 08:23
  • it looks different than the wanted. anway, please see edit. – Nina Scholz Mar 16 '21 at 08:26
  • My I know why did u put ??= – ahkam Mar 16 '21 at 14:04
  • it is a [logical nullish assignment `??=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment), like `a ??= []`, a short form of `a = a || []`. – Nina Scholz Mar 16 '21 at 14:07
  • Hello Nina Scholz. I just figured out. In the response it should be "name" and "permissions" instead "application" and "permission_name". Please update the answer if you can – ahkam Mar 18 '21 at 04:35
  • please see edit. – Nina Scholz Mar 18 '21 at 08:38