TransWikia.com

Trying to map an Array to an Object - Javascript

Stack Overflow Asked by mike varela on December 7, 2020

I’m using Angular and reactive forms and have a permissions object for access to items on page. Basically I’m trying to map the returned API array of objects to a formgroup set of formgroups. I’m not interested in formarray as I’ve got a lot depending on the structure that’s in the database.

But, having the hardest time trying to map this.


INITIAL STRUCTURE

[
{module_name: "users", access: true, edit: true, delete: false},
{module_name: "documents", access: true, edit: false, delete: false}
]

ANGULAR FORMS DESIRED STRUCTURE

accessControl: {
users: {access: true, edit: true, delete: false}
documents: {access: true, edit: false, delete: false}
}

3 Answers

Try the following using Array.prototype.reduce;

const input = [{
    module_name: "users",
    access: true,
    edit: true,
    delete: false
  },
  {
    module_name: "documents",
    access: true,
    edit: false,
    delete: false
  }
];

const output = input.reduce((acc, curr) => {
  const { module_name, ...rest } = curr;
  acc[module_name] = rest;
  return acc;
}, {});

console.log(output);

Correct answer by Alexander Staroselsky on December 7, 2020

Based on @Yair Cohen answer, but without specify parameters passed from data:

var accessControl = {};

var data = [
    { module_name: "users", access: true, edit: true, delete: false },
    { module_name: "documents", access: true, edit: false, delete: false }
];

data.forEach(x => {
    accessControl[x.module_name] = x;
    delete accessControl[x.module_name].module_name;
});
console.log({ accessControl });

Answered by Leo on December 7, 2020

Try this:

arr.forEach(module => {
   accessControl[module.module_name] = {
     access: module.access, edit: module.edit, delete: module.delete
  }
})

Answered by Yair Cohen on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP