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?
3 Answers 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;
});
Comments
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
const newArray = selectedRolesDB.reduce<{ [role: string]: boolean }>((accumulator, value) => { accumulator[value] = true; return accumulator; }, {});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
Explore related questions
See similar questions with these tags.