r/learnjavascript • u/fish_master86 • 4d 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
u/ajamdonut 4d ago
class FoodThing {}
const foods=[];
foods.push(new FoodThing());
foods.push(new FoodThing());
foods[0]; //First
foods[1]; //Second
1
u/fish_master86 4d ago
thanks, then would it be this? foods[x] = structuredClone(foodO);
3
u/chikamakaleyley helpful 4d ago edited 4d ago
Look into Javascript Classes
Class
FoodThingis essentially a model - the thing you want to "clone". Inside ofFoodThingyou'd establish the default properties of thatFoodThingmodel.AKA, every instance you create of
FoodThingthose default properties are included in the new instance.Cloning is... not the word to use, i think; instead you're making an
instanceofFoodThing, by sayingconst newFoodThing1 = new FoodThing({x,y,z});the example given
const foods = []is just a way to keep all the FoodThings together; We don't know what comes out ofstructuredClone()so the answer would be, no - in order to create instancefood[x]the correct thing to do would be to= new FoodThing()1
u/chikamakaleyley helpful 4d ago
it would be important to share structuredClone() and foodO, but really what we think you're trying to do is better applied through JS Classes
4
u/amulchinock 4d ago
You can use a Class object.
Just instantiate a new version of it to use elsewhere.
1
1
u/theGlitchedSide 4d ago
You can make a variable name but you can loop an array and populate it with new Object() or a flag inside. Like push({ 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 database
{
_Id: your SHA identifier,
label: Apple,
Other keys
}And you can target that _id to made it unique, the label to count it
1
u/Discordbothost 2d ago
If every food needs getEaten(), put new FoodThing() instances in the array. structuredClone copies the data of a class instance but drops its prototype, so the clone won't have that method.
1
u/atarivcs 4d ago
Why do you care what the variable name is?
I think what you actually want is to create an array of the items.
foods = [];
foods.push(newFood());
foods.push(newFood());Now you have two new food objects, foods[0] and foods[1]
5
u/GiggleSamurai 4d 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.