Reputation:
I have the following:
var data.roles = "Admin:Xxxx:Data";
for (role in data.roles.split(':')) {
if (role == 'Admin') { user.data.role.isAdmin = true }
if (role == 'Data') { user.data.role.isData = true }
if (role == 'Xxxx') { user.data.role.isXxxx = true }
if (role == 'Test') { user.data.role.isTest = true }
}
Is there a way that i could make this work without the if checks. What I would like is to have a solution that would work for any role that is present in data.roles.
Upvotes: 0
Views: 46
Reputation: 147413
Since split returns an Array, you could use forEach:
var data = {roles: "Admin:Xxxx:Data"};
var user = {data: {role:{}}};
data.roles.split(':').forEach(function(v) {
user.data.role['is' + v] = true;
})
console.log(user.data.role.isXxxx); // true
There is a polyfill at MDN for browsers without forEach.
Upvotes: 1