2

I am trying to convert an array into a javscript object that is designed to work with input checkboxes in AngularJS.

This is the input array that I get from my backend:

let selectedRolesDB = ['ADMIN', 'SECURITY'];

This is what my front-end expects:

let selectedRoles =
  {
    'ADMIN' : true,
    'SECURITY': true
  };

I tried different approaches such as angular.forEach but the problem is that I am not able to get the desired output:

angular.forEach(selectedRolesDB,(value, key) => {
    this.selectedRoles.push({value : true });
});

Can anyone tell me how I best solve my problem so I end up with the array that my front-end expects?

JSFiddle

3 Answers 3

3

selectedRoles is not array, it is object. Init it as empty object:

let selectedRoles = {};

angular.forEach(selectedRolesDB,(value, key) => {
    // use [] notation to add property with required name and value
    selectedRoles[value] = true;
});
Sign up to request clarification or add additional context in comments.

Comments

3

Use array.reduce :

    let selectedRolesDB = ['ADMIN', 'SECURITY'];
    const newArray = selectedRolesDB.reduce((accumulator, value) => {
       accumulator[value] = true;
       return accumulator;
    }, {});
    
    console.log(newArray)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce for documentation about it.

2 Comments

The question is marked with typescript, for typescript, you should also declare the type of the accumulator as depending on compiler flags you will get an error otherwise: const newArray = selectedRolesDB.reduce<{ [role: string]: boolean }>((accumulator, value) => { accumulator[value] = true; return accumulator; }, {});
Indeed, @TitianCernicova-Dragomir, however (according to the code provided in the question), the ts compiler does not use any specific flag and seems very permissive (also we cannot write a snippet in typescript :( )
0

Probably it would be much better to use array's native 'forEach' method (it has a good browser support, see here Array forEach). Also this will be helpful if you decide to migrate your project into Angular2+, so avoiding usages of 'angular.someMethod' is a better approach. This is a final solution:

const selectedRoles: {[key: string]: boolean} = {};
selectedRolesDB.forEach((value: string) => selectedRoles[value] = true);

Comments

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.