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

0

1 Answer 1

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

6
  • [ { 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
    Commented Mar 16, 2021 at 8:23
  • it looks different than the wanted. anway, please see edit. Commented Mar 16, 2021 at 8:26
  • My I know why did u put ??=
    – ahkam
    Commented Mar 16, 2021 at 14:04
  • it is a logical nullish assignment ??=, like a ??= [], a short form of a = a || []. Commented Mar 16, 2021 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
    Commented Mar 18, 2021 at 4:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.