2

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

1
  • can you show us your code where you try to map the structure and we point you what's wrong? Commented Aug 20, 2020 at 21:34

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

0

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

1 Comment

Also good. In fact I'm not sure about the parameters on the way in, it's not codified yet, so it can expand. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.