Search code examples
javascriptdatabaseforeachvar

Dynamically creating variables in a forEach loop - Javascript


So, I'm attempting to pass data through a forEach loop, creating a unique var for each piece of data passed. My code is as follows:

  data.forEach(function (data) {
    var name = data.Name;
  });
}

Is it possible to create a new 'name' var for each piece of data.Name data passed?

In other words: Is it possible to create a unique var and assign it dynamically to each name passed through the loop?

For example:

data set 1 is {Name: "Henry"}

data set 2 is {Name: "Chris"}

...

Is it then possible to make:

var1 = data set 1 ('Henry' )
var2 = data set 1 ('Chris')
...

By the way, an array doesn't work for my project, unfortunately. I'm attempting to isolate the individual data sets.

Thank you!


Solution

  • If I understand your question correctly you're attempting to store all of the names for later usage. If so you could probably go for something like:

    var names = [];
    data.forEach(function(d) {
        names.push(d.Name);
    }); 
    

    Or simply:

    var names = data.map(d => d.Name);