Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript map array of objects

Currently, I get the below output from the code,

[
  { module: 'subscriptions', action: [ 'create', 'edit' ] },
  { module: 'members', action: [ 'create' ] }
]

This is the expected output I want from the above output,

{
  "subscriptions": {
    "action": {
      create,
      edit
    }
  },
  "members": {
    "action: "{
      create
    }
  }
}

This is the code I tried,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let output = [
  { module: 'subscriptions', action: [ 'create', 'edit' ] },
  { module: 'members', action: [ 'create' ] }
]

output = 
output.map(({action, module}) => ({ [module]:action }) );
console.dir(output);

The above code currently gives me this wrong output,


[ { subscriptions: [ 'create', 'edit' ] }, { members: [ 'create' ] } ]

Could someone please help me to achieve the expected output?

>Solution :

By keeping an array for the nested properties, you could build new entries and then an object from it.

const
    data = [{ module: 'subscriptions', action: [ 'create', 'edit' ] }, { module: 'members', action: [ 'create' ] }],
    result = Object.fromEntries(data.map(({ module, action }) => [module, { action }]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading