I currently have an array as follows:
var allMenus = ['vehicleMakeFb','vehicleModelFb','vehicleTrimFb']
Where vehicleMakeFb etc. are actually objects. I originally tried to store the objects in the array, but I understand this is not possible in JS, so I have resorted to storing the names of the variables as strings.
My intention is to be able to iterate through the variables, and get individual properties of each, such as:
for (fbMenu in allMenus) {
alert(vehicleMakeFb.divId);
}
Where divId is a string.
What is the correct syntax to access this variable by its name?
-
1it is entirely possible to store objects in an array.thescientist– thescientist2011年06月23日 17:27:04 +00:00Commented Jun 23, 2011 at 17:27
-
Who told you that it's impossible to use JS to store objects in an array?Sparky– Sparky2011年06月23日 17:37:38 +00:00Commented Jun 23, 2011 at 17:37
3 Answers 3
What do you mean you can't store an array of objects?
var allMenus = [
{make: 'Ford', model: 'Mustang', trim: 'Coupe'},
{make: 'Ford', model: 'Explorer', trim: 'Eddie Bauer'}
];
// all items
for (var i = 0; i < allMenus.length; i++){
var fbMenu = allMenus[i];
// explicit list of properties
console.log('[X] Make: ' + fbMenu.make);
console.log('[X] Model: ' + fbMenu.model);
console.log('[X] Trim: ' + fbMenu.trim);
// discovered list of properties
for (var prop in fbMenu){
console.log('[D] ' + prop + ': ' + fbMenu[prop]);
}
}
2 Comments
for (var ... in ...) may be problematic across browsers (specifically IE). If you know the property names, use those. But you'll always be able to iterate over an array using a for (var ...; ....length; ...).You can access object properties in two ways:
Dot Notation
object.prop
Brackets
object['prop']
You can store objects in an array.
var arrayFullOfObjects = [{
foo: 'bar'
},
window,
jQuery
];
arrayFullOfObjects[0].foo; //bar
Comments
You can access the value of a property of a JS object using any of the following syntax:
// assuming the following object
var company = { employee : { name : 'foo' } };
// we can access the name property via
var name1 = company.employee.name;
var name2 = company.employee['name'];
var name3 = company['employee']['name'];
// ...
You can then store objects into arrays in much the same way:
var obj1, obj2, obj3; // some objects (initialized prior)
var myArray = [obj1, obj2, obj3];
Looking at your code, just make sure you ditch the quotes on your array JSON. (i.e. [obj], not ['obj']).