0

Hello I have a rather strange problem that doesn't make much sense. I have a variable that's a string, and I want to search a property of an object(that's also an object) with the same name. Like so:

var ObjectProperty; /// multi-layer object
var PropertyName; //string

and if there's a match to the PropertyName in the Object, I want to return it. Sample code:

OBJECT:
Bird.Raven = {
Name:"Raven",
Color:"Black",
} 
//Object

Bird.Duck = {
Name:"Duck",
Color: "Gray",
} 
//Object

Bird.Cardinal = {
Name:"Cardinal",
Color: "Red",
}//Object
///ObjectProperty sample.

Key I want to find inside "Bird":

var Cardinal = "Cardinal"; //string
///PropertyName sample.

Current Function I'm using, assume 'n' is the PropertyName variable I want to search:

var searchBirds = function(n) {
  for(var key in Bird) {
    var keyName = key.toString();
  if(keyName == n){
  console.log("bird " + key + " has been found.");
  console.log(typeof key);//RETURNS STRING
  return key;
  }
  else{
  console.log(n + " could not be found")
  };
  }
  }

Why is it returning a string when this should be an object? How can I make it return the key as an object? What's wrong? Vanilla Javascript preferred.

Thanks for the help, I hope this makes sense!

1 Answer 1

4

The statement for(var key in Bird) iterates through the names of the enumerable properties on the Bird object. To get the value of that property, do Bird[key].

Example:

var key, birdObject;
for (key in Bird) {
    birdObject = Bird[key];
    console.log(key + ".Color = " + birdObject.Color);
}

...would output

Raven.Color = Black
Duck.Color = Grey
Cardinal.Color = Red

...in no specified order (although nearly all engines will do them in the order the properties were added to the object [provided none of the property names is all digits, in which case there's more variation] — but that's not in the spec).

2
  • While I don't quite follow with the brackets and keys and properties(though I'm working on that) I have to say this works magic! Thanks! Nov 1, 2013 at 18:28
  • @user2588440: :-) Object properties have names. There are two ways we can give the JavaScript engine the name of the property we want: Either by typing it as an "identifier," literally in the text, like the "height" in this: a.height, or by giving it to the engine as a string: a["height"]. The engine knows which of those we're doing because we use a . with the identifier, but we use [...] with the string. It's just two different ways of doing the same thing. And if we're using a string, it can be any string, so a["he" + "ight"] works, and key1 = "height" then a[key1] works. Nov 1, 2013 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.