Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate thru Hashtable while checking each key, value pair Javascript [duplicate]

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.

like image 954
Psyllex Avatar asked Sep 27 '12 18:09

Psyllex


People also ask

Can you iterate through a Hash table?

There are various ways by which we can iterate through the HashTable which are as follows: Using Enumeration Interface. Using keySet() method of Map and Enhance for loop. Using keySet() method of Map and Iterator Interface.

How do you add a key value pair in an object dynamically?

You need to define an object and use square bracket notation to set the property; var obj = {}; obj[name] = val; ary. push(obj);


1 Answers

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();
}
like image 137
pce Avatar answered Nov 06 '22 23:11

pce