r/learnjavascript • u/fish_master86 • 2h ago
How do I make multiple objects with different names from the same code?
function makeNewFood() {
totalNumOfFood = totalNumOfFood + 1;
let (foodOClone+totalNumOfFood) = structuredClone(foodO);
};This is my pseudocode I need help with. I want it to make a new object called "foodOClone1" then "foodOClone2" etc.
Thanks for the help.
For next time: Did I include enough detail and if not, what other details can I include
1
Upvotes
2
u/GiggleSamurai 1h ago
JavaScript can't build variable names at runtime like that, so put the clones in an array instead: `const foodClones = [];` and inside the function `foodClones.push(structuredClone(foodO));`. Then you get them back with `foodClones[0]`, `foodClones[1]` and so on, and `foodClones.length` replaces your counter.
2
u/ajamdonut 1h ago
class FoodThing {}
const foods=[];
foods.push(new FoodThing());
foods.push(new FoodThing());
foods[0]; //First
foods[1]; //Second
3
u/amulchinock 1h ago
You can use a Class object.
Just instantiate a new version of it to use elsewhere.
2
u/atarivcs 41m ago
Why do you care what the variable name is?
I think what you actually want is to create an array of the items.
Now you have two new food objects, foods[0] and foods[1]
1
u/ray_zhor 1h ago
This is exactly why classes were made. Store your clones in an array
1
u/theGlitchedSide 1h ago
You can make a variable name but you can loop an array and populate it with
new Object()or a flag inside. Likepush({ random name: value})and make new name continually. It's silly, but the same object does not have a name, it's literally a{ something }so, the better idea is generate an ID like databaseAnd you can target that _id to made it unique, the label to count it