Mike Varela
Mike Varela

Reputation: 527

Trying to map an Array to an Object - Javascript

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

Upvotes: 2

Views: 58

Answers (3)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38767

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

Upvotes: 4

Leo
Leo

Reputation: 2350

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

Upvotes: 0

Yair Cohen
Yair Cohen

Reputation: 2258

Try this:

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

Upvotes: 1

Related Questions