Home > database >  Append record number to variable name when looping array
Append record number to variable name when looping array

Time:10-25

I'm brand new to javascript and appreciate everyone's help. I'm looping an array that might have 5 to 10 different records in it. This is what I'm doing so far and it works just fine. I didn't think including the array was necessary but let me know if it is.

obj = relatedActivities.data;
console.log(obj);

  for (var i = 0; i < obj.length; i  ) {
     var activityType = (obj[i].Activity_Type)
    }

The only problem with this is I need to put each record's value in a particular place. What I want is a different variable every time it loops.

So the first record, the variable name would be something like:

activityType0 = obj[0].Activity_Type

and for the second record it would be:

activityType1 = obj[1].Activity_Type

I hope that makes sense.

Thank you all much!

CodePudding user response:

While I'm not sure there is any practical use for doing this, I will post this for the sake of answering the question.

Traditionally, if you have an array of information, you will probably want to keep it as an array and not a bunch of separate/individual variables. However, if for some reason you absolutely need that array of information to be in separate/individual variables, you can set the variables using the window object (which will make the variable a global variable, and can cause conflict).

relatedActivities.data.forEach((obj, i) => {
    window[`activityType${i}`] = obj.Activity_Type
});

console.log(activityType0);
console.log(activityType1);

Basically any global variable is typically called by its variable name, like activityType0. However, you can also call it through the window object like so: window.activityType0 or window["activityType0"]. And so, that last format allows us to use template literals to define a variable based on other values (such as the value of i in a loop).

CodePudding user response:

Well | maybe you hope so,This is basically the same answer as above | except that we avoid namespace pollution

relatedActivities.data.forEach((o, i,arr) => {
   arr[i] = {}; 
   arr[i][`activityType${i}`] = o.activityType;  
})

relatedActivities.data.forEach(o => console.log(o))
  • Related