0
var validCoins = {
      "nickel": {
        "weight": 5.00,
        "diameter": 21.21,
        "thickness": 1.95,
        "value": 0.05
      },
      "dime": {
        "weight": 2.27,
        "diameter": 17.91,
        "thickness": 1.35,
        "value": 0.10
      },
      "quarter": {
        "weight": 5.67,
        "diameter": 24.26,
        "thickness": 1.75,
        "value": 0.25
      }
    };

Method 1:

Object.keys(validCoins).forEach(function(coinType) {
      alert(coinType.weight);
}

Method 2:

for (var key in validCoins){
//Checking for hasOwnpProperty here doesn't make a difference
        alert(key["weight"]);
    }

None of these seem to work, it returns undefined, what am I missing? (Do I have to import libraries or something?) I intend to do this using plain javascript.

titanium
  • 5
  • 1
  • 2
  • 1
    `Object.keys` gives you... wait for it... the object's keys! Use `validCoins[coinType].weight` –  May 07 '16 at 01:12
  • 1
    Do `alert(coinType)`. – Felix Kling May 07 '16 at 01:12
  • That's not what I want @FelixKling also I already saw that post but didn't get the answer. – titanium May 07 '16 at 04:24
  • You haven't completely read the answer then. Section *"What if the property names are dynamic and I don't know them beforehand?"* describes how to iterate over properties. And explains exactly what the answer you accepted shows. – Felix Kling May 07 '16 at 04:31

1 Answers1

1
var validCoins = {
      "nickel": {
        "weight": 5.00,
        "diameter": 21.21,
        "thickness": 1.95,
        "value": 0.05
      },
      "dime": {
        "weight": 2.27,
        "diameter": 17.91,
        "thickness": 1.35,
        "value": 0.10
      },
      "quarter": {
        "weight": 5.67,
        "diameter": 24.26,
        "thickness": 1.75,
        "value": 0.25
      }
    };

for (var key in validCoins) {
  if (validCoins.hasOwnProperty(key)) {
    alert(validCoins[key].weight);
  }
}

Fiddle