Chrisissorry
Chrisissorry

Reputation: 1514

Reading Object Literal in JS with function result

I have an object literal:

var content = {
    classname1:"content",
    classname2:"content"
}

Accessing in this way content.classname1 is easy. But I do not want to state classname1 rather than using a function to get that classname and pass it to my object:

function getMyClass {
 // some code
 return myclass;
}

content.myclass 

where myclass is the result of a function. But that does not work. I do not know how to concatenate the content. with the result of the function.

The background is: I want tooltips to be displayed for nearly everthing on my site. So one function schould find out the class of the element and then display it the content associated to it from the object literal. So managing classname and content would be pretty easy.

Thanks.

Upvotes: 0

Views: 238

Answers (3)

Ken Redler
Ken Redler

Reputation: 23943

If you want to use a function (perhaps there's more logic than simply selecting the value of a property), here's one way:

var content = {
  classname1:"contentbbbb",
  classname2:"contentaaaa",
  getClassName : function(which){
    // do stuff, check things
    return this[which];
  }
}

Then you'd have:

content.getClassName('classname1'); // returns 'contentbbbb'

Upvotes: 0

Raynos
Raynos

Reputation: 169391

function getMyClass {
    // some code
    return "myclass";
}

content["myclass"];

This might be what your looking for. Your question is a bit vague.

Alternatively you could try:

for (var key in content) {
    if (content.hasOwnProperty("key")) {
         addContent(key, content[key]);
    }
}

function addContent(className, content) {
    // do stuff
}

Upvotes: 0

Jason LeBrun
Jason LeBrun

Reputation: 13293

obj.property is syntactic sugar for obj['property']

You can access the members of an object using [] notation instead of dotted notation. If you use brackets, then you can place anything that evaluates to a string between the brackets. This allows you to dynamically specify properties, or to use property names that aren't valid JavaScript identifiers... for example obj['2nd property']

So, try:

content[getMyClass()]

Upvotes: 2

Related Questions