我在代码中遇到了一种情况,我有三个Java脚本变量,其中两个是数组,一个是单个字符串变量。以下是它们的结构:

var selectedUser = $('#Employees_SelectedValue').val(); //It has one one value "12121"
var selectedCountries = $('#Countries_SelectedValue').val();  //It has multiple values ["IND", "USA"]
var selectedSourceSystems = $('#SourceSystems_SelectedValue').val(); //It has multiple values ["SQL", "ORACLE", "MySQL"]


我要做的是将这些值添加到基于selectedUser的类中,例如User的所有值都相同,但其余两个值不同,例如:

var userSettings = { userName: selectedUser, userCountry: selectedCountries, userSourceSystem: selectedSourceSystems };


情况是将此类的值添加到数组中,以使每个userCountry和userSourceSystem都作为一个单独的实体出现,例如:

{ userName: "12121", userCountry: "IND", userSourceSystem: "SQL" },
{ userName: "12121", userCountry: "USA", userSourceSystem: "ORACLE" },
{ userName: "12121", userCountry: "", userSourceSystem: "MySQL" }


我正在尝试使用嵌套循环的方法来处理这种情况,例如:

for (var i = 0; i < selectedCountries; i++)
        {
            for (var j = 0; j < selectedSourceSystems; j++)
            {
                userSettings.userName = selectedUser;
               //Add i and j values
            }
        }


请提出除此以外的有效方法。

最佳答案

您可以设置3×n矩阵(二维数组)并将其旋转90度:

var matrix = [[selectedUser],selectedCountries,selectedSourceSystems];

var result =
   Array(//set up a new array
     matrix.reduce((l,row)=>Math.max(l,row.length),0)//get the longest row length
   ).fill(0)
   .map((_,x)=> matrix.map((row,i) => row[i?x:x%row.length] || ""));


Result

如果结果应包含对象,则将2d数组映射到对象:

var objects = result.map(([a,b,c])=>({userName:a,userCountry:b,userSourceSystem:c}));


result

小说明:

row[i?x:x%row.length] || ""


实际上执行以下操作:

If were in the first row ( i=0 ) ("12121")
  take whatever value of the array (x%row.length), so basically always "12121"
if not, try to get the value of the current column(x)
  if row[x] doesnt exist (||) take an empty string ("")




一个更基本的方法:

var result = [];
for(var i = 0,max = Math.max(selectedCountries.length,selectedSourceSystems.length);i<max;i++){

  result.push({
    userName:selectedUser,
    userCountry:selectedCountries[i]||"",
    userSourceSystem:selectedSourceSystems[i]||""
  });
}


result

10-06 04:59