ill keep this simple, because other examples have been complicated and I havent been able to follow.
i have an array
var bigArray = ["cat", "dog","mouse"];
I would like to take this and create new (3) arrays based on the objects in the array
var cat =[];
var dog =[];
var mouse =[];
seemingly, this does not work.
bigArray.forEach(let array[element] = new Array(array[element]));
console.log(arraycat);
CodePudding user response:
You can't really create variables dynamically, except if you make them global by binding them to the window
object, which is not a good idea.
A common way of doing this is to create an empty object, then store whatever you want inside by adding key/value pairs to it.
const bigArray = ["cat", "dog","mouse"];
let animals = {};
bigArray.forEach( species => animals[species] = [ 1, 2 ,3, 4 ] );
console.log("cat = ", animals.cat)
console.log("dog = ", animals.dog)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
var bigArray = ["cat", "dog","mouse"];
bigArray.forEach(function(item) {
window[item] = [];
});
console.log(window.cat);
console.log(window.dog);
console.log(window.mouse);
// or
console.log(cat);
console.log(dog);
console.log(mouse);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
If you are using web browsers, you can bind them to window
.
Provided this wont work with nodejs or javascript framework working for non web browsers.
var bigArray = ["cat", "dog","mouse"];
bigArray.forEach(node => {
window[node] = [];
});
console.log(cat, dog, mouse);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The above solution is considered as a bad practice. If you just want to have nodes with same name as in array, you can create this node inside an object just like below.
const bigArray = ["cat", "dog","mouse"];
const myObj = {};
bigArray.forEach(node => {
myObj[node] = [];
});
console.log(myObj.cat, myObj.dog, myObj.mouse);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If you need to create distict variables, you can use the first approach.
If you are ok to use the same nodes from an object, you can use the second approach.