2017-07-31 147 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無需*填寫*,你可以簡單地把它放進去。 –