user2906420
user2906420

Reputation: 1269

JavaScript: Getting an objects property value

I am wandering if this is possible below:

var layers = {};
layers.group3 = new L.MarkerClusterGroup(); //some group of objects 
layers.group3.name = "somestr"; //here i want to give a property name to group3 object. 


function checkLayers(data, t) {

    for (var name in layers) {
         var value = layers[name];
         alert("name: "+name+ " value: "+value);

         if(layers.group3.name == t){
             //do something
         }
    }     
}

How can i access the name property for group3. It does not show up in the alert. And I also want to compare the value to parametar "t".

Upvotes: 0

Views: 56

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

If you want to get the name property through iteration, you must check if the property name for the iteration is group3. Once you are sure you have the group3 property you can access the name property. The for...in loop will iterate over every property of an object, when using in layers it iterates over all of layers properties, since group3 is a property on layers you cannot access the group3.name property by simply iterating over the properties in layers.

for (var name in layers) {
     if(name == "group3" && layers[name].name = t){
         delete layers[name];
     }
} 

This can be done much simpler without iteration:

alert(layers.group3.name);

Upvotes: 1

Verych
Verych

Reputation: 441

I modified your code. It works fine:

var layers = {};
layers.group3 = {};
layers.group3.name = "somestr"; //here i want to give a property name to group3 object. 


function checkLayers(data, t) {

    for (var name in layers) {
         var value = layers[name];
         console.log("name: ", name , " value: " , value);

         if(layers.group3.name == t){
             console.log(layers.group3.name);
         }
    }     
}
checkLayers('', 'somestr');

Results in console:

name:  group3  value:  Object {name: "somestr"} 
somestr 

Upvotes: 0

Related Questions