How to convert/use a variable string in javascript object property

Viewed 35

I am not sure if my question title makes sense. Basically I have a number of objects and want to reference a specific one based on a variable.

For example I have these objects in a store called data using Pinia:

var obj1 = ref([{name:"Doug",title:"main character"},{name:"Porkchop",title:"dog"}]);
var obj2 = ref([{name:"Patty",title:"Other character"},{name:"Skeeter",title:"friend"}]);

My code looks at a variable based on the route param/URL, and I want to use that to pick which object from above.

var myVar = "obj2"; <- this is an example and is dynamic based on URL updated in a function when mounted.

Then I want to loop one of the objects like below:

  Object.keys(data.obj1).forEach((k, i) => {
    formData.append(data.obj1[k].name, data.obj1[k].title);
  });

I cannot figure out how to dynamically change the data.->HERE<- to what I need. I have tried dynamically setting the property (if that is the correct term.).

data.myVar    
data.[myVar]

For clarification, I am not trying to modify the values of anything. I just want to change the reference of the object based on a variable.

I just want to avoid hard coding a switch statement or something... if possible.

Thank you, and let me know if you need clarification or the examples don't make sense.

0 Answers
Related