I know there are a ton of questions about eval()
alternatives, but I don't think I've come across anything like what I'm trying to do. I apologize if I've come across an answer and just didn't realize it.
Instead of creating a bunch of variables like this
let layerHomes = L.layerGroup().addTo(map);
let layerBusinesses = L.layerGroup().addTo(map);
let layerParks = L.layerGroup().addTo(map);
How would I do it like this, but without eval()
?
array = ['Homes', 'Businesses', 'Parks'];
array.forEach((name) => {
let layer = `$layer{name} = L.layerGroup().addTo(map)`;
let polylines = `$layer{name}Polylines = L.layerGroup().addTo(map)`;
eval(layer);
eval(polylines);
});
I've tried using Function()
...
collections.forEach((array) => {
new Function(array, `let layer${array} = L.layerGroup().addTo(map);`);
new Function(array, `let layer${array}Polylines = L.layerGroup().addTo(map);`);
});
...but I'm receiving an error: Unhandled Promise Rejection: ReferenceError: Can't find variable: layerHomesPolylines
Which is weird, because layerHomes
doesn't throw an error, but layerHomesPolylines
does?
How do I accomplish this without eval?