0

my structure looks like this:

    var Menu = {
      crab    : 5,
      lobster : 4,
      potato  : 10,
      rib     : 3,
      wings   : 8
    }, // foodcount1-4 represent the HTML mapping  
  foodCount1 = document.getElementById('crab'),    
  foodCount2 = document.getElementById('lobster'),    
  foodCount3 = document.getElementById('potato'),    
  foodCount4 = document.getElementById('rib'),    
  foodCount5 = document.getElementById('wings');

I can't figure out how to access any of the individual variables. I've tried indexing into the object( Menu.i) and I've tried grabbing the other variables like an array (Menu[1]) but I can't seem to get it.

EDIT: Here's what I want to know:

How do I access the other items in the variable? i.e. I have var menu = {...}, food1, food2, food3; how to I get to food1,2 and 3?

2 Answers2

1

If you just need to access any data of your Menu object, simply use Menu.crab or Menu["crab"]. It's a duplicate of javascript "associative" array access.

Community
  • 1
  • 1
Renaud Michotte
  • 389
  • 4
  • 17
0
// Access a member in JS Object
var Menu = {
  crab    : 5,
  lobster : 4,
  potato  : 10,
  rib     : 3,
  wings   : 8
};
Menu.crab; // => 5
Menu['rib']; // => 3

// Loop members in JS Object
Object.keys(Menu).forEach(function(key) {
   console.log(key); // => 'crab', 'lobster', ...etc
   console.log(Menu[key]); // => 5, 4, ...etc
});

Update

var foo = {test: 'abc'}, var1 = 1, var2 = 2;
// is equal to
var foo = {test: 'abc'};
var var1 = 1;
var var2 = 2;
Fan Jin
  • 2,412
  • 17
  • 25
  • But how would I access the other items in the variable? i.e. I have var foo = {...}, var1, var2, var3; how do I get to var1,var2, or var3? –  Oct 26 '16 at 18:10
  • Simply by calling them. var foo = {...}, var1, var2, var2; is equal to var foo = {...}; var var1; var var2; var var3; – Fan Jin Oct 26 '16 at 18:20
  • Would I call them as foo[1] = var1, foo[2] = var2, etc.? –  Oct 26 '16 at 18:21
  • No, `var1`, `var2` is not a part of `foo`. They are separate variables. – Fan Jin Oct 26 '16 at 18:26
  • oh thank you so much! What is the purpose for linking variables like this; does it just save space? –  Oct 26 '16 at 18:27
  • 1
    Usually we want to avoid this. Indent them if you don’t want to write extra vars. Did I answer your question? – Fan Jin Oct 26 '16 at 18:40
  • Would you like to mark my answer as the correct answer? Thanks! :^) – Fan Jin Oct 26 '16 at 18:54