簡體   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