简体   繁体   English

Javascript 将数组值从 boolean 切换到字符串

[英]Javascript switch array values from boolean to string

I have this 2 dimensional array =我有这个二维数组=

0: (3) [true, false, false]
1: (3) [true, true, false]
2: (3) [true, true, true]
3: (3) [false, false, false]

The position in the array represents the same in each ie 0 = "Learner" 1 = "Manager", 2 = "ClientAdmin"数组中的 position 在每个中表示相同,即 0 = "Learner" 1 = "Manager", 2 = "ClientAdmin"

I want a new 2 dimensional array that looks like below我想要一个新的二维数组,如下所示

0: (3) ["Learner"]
1: (3) ["Learner", "Manager"]
2: (3) ["Learner", "Manager", "ClientAdmin"]
3: (3) []

I have tried我努力了

selectedAudienceMandatoryArrayText = []

this.selectedAudienceMandatoryArray.forEach( (isArray, index) => {
          if (isArray[0] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("Learner");
          }
          if (isArray[1] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("Manager");
          }
          if (isArray[2] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("ClientAdmin"); 
          }
        }

but I get the error: Cannot read property 'push' of undefined但我收到错误: Cannot read property 'push' of undefined

What is the most efficient way to do this.什么是最有效的方法来做到这一点。 ES6 solutions welcome.欢迎使用 ES6 解决方案。

You could check if the flag is set, then take the value from roles with the index or return an empty array.您可以检查是否设置了标志,然后从具有索引的roles中获取值或返回一个空数组。

 const roles = ["Learner", "Manager", "ClientAdmin"], data = [[true, false, false], [true, true, false], [true, true, true], [false, false, false]], result = data.map(a => a.flatMap((f, i) => f? roles[i]: [])); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

selectedAudienceMandatoryArrayText = [];

this.selectedAudienceMandatoryArray.forEach(isArray => {
  const roles = [];
  
  if (isArray[0]) roles.push('Learner');
  if (isArray[1]) roles.push('Manager');
  if (isArray[2]) roles.push('ClientAdmin');
  
  selectedAudienceMandatoryArrayText.push(roles);
}

You could push to a new array for each loop, and at the end, push that to the other array.您可以为每个循环推送到一个新数组,最后将其推送到另一个数组。 This reduces having to keep track of the index for the outer array.这减少了跟踪外部数组的索引。

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

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