简体   繁体   中英

JavaScript nested for-loop to add values to an object

I have encountered a situation in my code where I have three java script variables in which two are arrays and one is a single string variable. The following are their structure:

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"]

What I have to do is to add these values in a class on the basis of selectedUser such as User is same for all the values but the remaining two are different as:

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

The situation is to add the values from this class into an array in such a way that every userCountry and userSourceSystem will come as a single entity such as:

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

I'm trying the approach of nested-for loop to handle this scenario like:

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

Please suggest an effective approach other than this.

You may set up a 3×n matrix ( a 2d array) and rotate it by 90 degrees:

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

If result should contain objects, then map the 2d array to objects:

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

result

Small explanation:

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

Actually does the following:

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 ("")

A more basic approach:

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

I believe it would be better to restructure your userSettings object in more natural way:

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

Then you can fill it with settings from your inputs like this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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