繁体   English   中英

JavaScript嵌套的for循环可将值添加到对象

[英]JavaScript nested for-loop to add values to an object

我在代码中遇到了一种情况,我有三个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] || ""));

结果

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

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

结果

小说明:

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]||""
  });
}

结果

我相信以更自然的方式重组userSettings对象会更好:

userSettings: {
    name: "userName",
    countries: ["USA", "IND"],
    userSourceSystems: ["MySQL", "Oracle"]
}

然后,您可以像这样从输入中填充设置

for (item in selectedCountries)
    userSettings.countries.push(item)

for (item in selectedCountries)
    userSettings.userSourceSystems.push(item)

暂无
暂无

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

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