12

Possible Duplicate:
How do I enumerate the properties of a javascript object?

I"m trying to iterate thru a hashtable. But I need to check the values each time I run through it.

How would I use a foreach table to do this? in sudo code I'd like to do this:

var tHash = {
 name: n,
 date: d,
 labels: l,
}

foreach(value in tHash){
   if(tHash.name== somevalue){do something};
   if(tHash.label == somevalue) {do something};

That's essentially what I'd like to do but not real sure how to start it out.

Edit: The isn't just one hash it's an array of hashes...I should've mentioned that at the beginning the way I put the code is the way I was loading the array of hashes with a for loop.

Community
  • 1
  • 1
John Verber
  • 745
  • 2
  • 16
  • 31
  • If you know what you want each property to be, you shouldn't need a loop. Just check the value of each property. – James Allardice Sep 27 '12 at 18:42
  • well I basically have a huge list of names date label pairs. I'm putting them into Google spreadsheet and so I need to check the name first(so I don't duplicate) and then the label second(since there are 4 different label types and I only want to add to the sum of the label that is in the current key/value pair). – John Verber Sep 27 '12 at 18:50
  • you can check the property "name" within a for...in loop. – pce Sep 27 '12 at 19:08

2 Answers2

28

You can iterate through the Keys of a Hashobject with a for ... in Loop. You get each property (key) of the Hash and can also access the Value with the property.

var tHash = {
  name: "n",
  date: "d",
  labels: "l" 
}

for (var key in tHash){
  console.log(key + " -> " + tHash[key]));   
  // if (key == "name") doSomething();
}
Anil
  • 2,539
  • 6
  • 33
  • 42
pce
  • 5,571
  • 2
  • 20
  • 25
-3

This works, as is.

var tHash = {
 name: "Jeremy",
 date: "0",
 labels: 4
}

if (tHash.name === "Jeremy") {alert("Welcome, Master")};
if (tHash.labels !== 0) {alert("There is a label waiting")};
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74