简体   繁体   English

将字符串转换为_.each中的对象

[英]Turn string to object within _.each

I'm using underscore in an Angular controller and attempting to turn a string into an object with several properties. 我在Angular控制器中使用下划线,并尝试将字符串转换为具有多个属性的对象。

vm.availableGames = _.each(availableGames, function(game) {
  game.name = game;
  if (_.contains(user.allowed_games.games, game)) {
    game.allowed = true;
  } else {
    game.allowed = false;
  }
});

availableGames is an array of strings of available games allowed_games is also an array of strings of allowed games availableGames是一组可用游戏的字符串allowed_games也是一组允许的游戏字符串

My aim is to create an array of objects ( vm.availableGames ) which contains all available games. 我的目标是创建一个包含所有可用游戏的对象数组( vm.availableGames )。 Each of these objects will have a name property (the original string) and an allowed property (a boolean). 这些对象中的每一个都有一个name属性(原始字符串)和一个allowed属性(布尔值)。

The above code results in a Cannot assign to read only property... error. 上面的代码导致Cannot assign to read only property...错误。 How would I go about accomplishing what I'm aiming for without running into this error? 在不遇到此错误的情况下,我将如何实现我的目标?

this should work: 这应该工作:

vm.availableGames = _.map(availableGames, function(game) {
  return {
    name: game,
    allowed: _.contains(user.allowed_games, game)
  };
});

and without underscore: 并且没有下划线:

vm.availableGames = availableGames.map(function(game) {
  return {
    name: game,
    allowed: (user.allowed_games.indexOf(game) !== -1)
  };
});

It's not underscore, but will this work? 它不是下划线,但是可以工作吗?

vm.availableGames = [];

for( game in availableGames ) {
    if( allowed_games.indexOf(game) !== -1 )
        vm.availableGames.push({ allowed: true, name: availableGames[game] });
    else
        vm.availableGames.push({ allowed: false, name: availableGames[game] });
}
for( game in allowed_games ) {
    if( availableGames.indexOf(allowed_games[game]) !== -1 )
        vm.availableGames.push({ allowed: true, name: allowed_games[game] });
}

EDIT: Answer using forEach... 编辑:回答使用forEach ...

NOTE: This only works if everything in allowed_games is also in availableGames. 注意:仅当allowed_games中的所有内容也都在availableGames中时,此方法才有效。

availableGames.forEach(function( game ) {
    vm.availableGames.push({ allowed: allowed_games.indexOf(game) !== -1, name: game });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM