r/learnjavascript • • 3d 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

6 Upvotes

15 comments sorted by

5

u/GiggleSamurai 3d 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.

3

u/fish_master86 3d ago

ok thanks. To get the variables or run functions it would be like this? foodClones[x].getEaten();

4

u/Forward_Dark_7305 3d ago

Exactly right (of course assuming your object itself has a `getEaten` member).

You’ll want to look up information about a few things for this if you don’t yet know about them:

Array - to store a dynamic list of items, and access them by numeric index
Map - to store a dynamic list of items and access them by name or some other key
Loops, specifically `for (let i=0; i < myArray.length; i++) { }` style loops, will probably help you understand arrays and indexing.

Early in my programming career I found myself trying to do something similar in a language that does support dynamic variable naming. Problem is, if you can only instantiate it dynamically you will (almost certainly) only access it dynamically and at that point you lose the static access benefits that putting it in a named variable provide - so you might as well use an array, map, etc.

0

u/Own_Giraffe987 2d ago

Using an array is a solid approach, but if you want unique names for each clone, consider storring them as properties in an object, like `foodClones[I] = { name: 'foodOClone' + I, value: structuredClone(foodO) }`. Then you keep both the name and the clone.

1

u/thealjey 2d ago

well, it can if you make them global as in (globalThis["foodOClone" + totalNumOfFood] = ...), although I am obviously not suggesting anyone actually do this 😄

0

u/senocular 2d ago edited 2d ago

eval (or the Function constructor) can also do it

let totalNumOfFood = 0
const foodO = { isFood: true }
function makeNewFood() {
  totalNumOfFood = totalNumOfFood + 1;
  eval(`var foodOClone${totalNumOfFood} = structuredClone(foodO)`);
  console.log(foodOClone1) // { isFood: true }
}
makeNewFood()

But its probably for the better no one is pointing that out ;)

1

u/ajamdonut 3d ago

class FoodThing {}

const foods=[];

foods.push(new FoodThing());
foods.push(new FoodThing());

foods[0]; //First
foods[1]; //Second

1

u/fish_master86 3d ago

thanks, then would it be this? foods[x] = structuredClone(foodO);

3

u/chikamakaleyley helpful 3d ago edited 3d ago

Look into Javascript Classes

Class FoodThing is essentially a model - the thing you want to "clone". Inside of FoodThing you'd establish the default properties of that FoodThing model.

AKA, every instance you create of FoodThing those default properties are included in the new instance.

Cloning is... not the word to use, i think; instead you're making an instance of FoodThing, by saying

const 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 of structuredClone() so the answer would be, no - in order to create instance food[x] the correct thing to do would be to = new FoodThing()

1

u/chikamakaleyley helpful 3d 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 3d ago

You can use a Class object.

Just instantiate a new version of it to use elsewhere.

1

u/ray_zhor 3d ago

This is exactly why classes were made. Store your clones in an array

1

u/theGlitchedSide 3d 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 1d 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 3d 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]