0

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?

2
  • 1
    it is entirely possible to store objects in an array. Commented Jun 23, 2011 at 17:27
  • Who told you that it's impossible to use JS to store objects in an array? Commented Jun 23, 2011 at 17:37

3 Answers 3

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]);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, thanks... looks like I read some duff info about not being able to store JS objects in arrays.
@HO: Not a problem, glad to help. Just be aware, the 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; ...).
1

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

1

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']).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.