0

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 1
    possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) (possibly along with a filter), `user.data.role["is" + role] = true;` – user2864740 Jun 19 '14 at 06:09
  • how about indexing with the string itself? `user.data.role[role] = true;` – The Paramagnetic Croissant Jun 19 '14 at 06:09

1 Answers1

1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thank you very much. I have a follow up question I will post in the next 5 minutes. Similar data but I need to set the value of a variable based on if or if not the roles are present. Hope you can help out with that too. –  Jun 19 '14 at 06:28