2017-07-31 53 views
0

我遇到了我的代码中的情况,我有三个java脚本变量,其中两个是数组,一个是单个字符串变量。以下是它们的结构:JavaScript嵌套for循环向对象添加值

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的基础上,如用户对这些值是相同的所有值,但其余两个是不同的:

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循环来处理这种情况的方法,例如:

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

请建议除此以外的有效方法。

+1

起初分化*类填充它从你的输入请*,*对象*和*数组*。你已经把它们混合了一下... –

+1

你已经做了一个对象userSettings,然后把它当作一个数组userSetting [0]处理。你想做什么。 –

+1

这是无效的语法 - >'{“12121”,“IND”,“SQL”}'。错误将是“意想不到的令牌”, – Jamiec

回答

1

可在90度设置的3×n矩阵(二维阵列)并将其旋转:

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

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

+0

这就是我要找的。非常感谢好友。就像你已经计算了最大长度并迭代循环直到它大于0,我正在使用嵌套for循环尝试相同的事情。但是这种方法看起来更简单和高效。欢呼声 –

+0

@sahil sharma youre welcome;) –

0

我相信这将是更好的重组你的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) 
+0

Theres无需*填写*,你可以简单地把它放进去。 –