What I mean is, say I have this object:
var myObject = [{
name:"Name1",
text:"text1",
array:"firstArray"
},{
name:"Name2",
text:"text2",
array:"secondArray"
}];
Later in the code there is this:
useArray=[];
firstArray=['a','b','c'];
secondArray=['x','y','z'];
Then, there's a conditional statement that decides which array will be used, but instead of hand typing it out like this:
if(selection = "Name1"){
useArray = firstArray;
}
else if(selection = "Name2"){
useArray = secondArray;
}
I want to be able to have it dynamic, so that no matter how long the object is it will work. Like this:
for(i=0;i<myObject.length;i++){
if(selection == myObject[i].name){
useArray = myObject[i].array;
}
}
But unfortunately this doesn't work. In the object I've even tried taking out the quotation marks around the array and declaring the array before the object but that doesn't work either.
The array comes up empty or undefined.
I know it has to do with being a string or something so what is the workaround to accomplishing this?
I realize I should have made my arrays differently. What if the arrays are actually just more objects? The answers below look beautiful and I think Amit's and other answers that look similar will do the trick. But the difference with the problem I am actually attempting to solve is that first of all, my arrays start out empty, so here I have:
var myObject = [{
name:"Name1",
text:"text1",
array:[]
},{
name:"Name2",
text:"text2",
array:[]
}];
Then I've added:
var arrays={
firstArray:[],
secondArray:[]
}
Again, it starts out empty. As specified in my original question, later in the code the arrays are filled. To be more exact and clear, this is how it is being done:
arrays.firstArray.push({
floor:myObjects[c].name, text:myObject[c].text
});
It is in a for loop but that is irrelevant.
My for loop set up just like this one:
for(i=0;i<myObject.length;i++){
if(selection == myObject[i].name){
useArray = arrays[myObject[i].array];
}
}
But when I alert useArray
, it is blank. Is this because the array I am using is actually an object?