views:

30

answers:

2

I have an object that contains another object with translations. It looks like this:

var parent = { //parent object with a bunch of stuff in it
    countryAlerts:{ //area for country alerts
        "USA":{ //country
            en:"FAST", //alert text in English
            es:"RAPIDO" //alert text in Spanish
        },
        "Japan":{
            en:"FAST",
            es:"RAPIDO"
        }
    }
}

I would like to do something like this:

var parent = {
    countryAlerts:{
        "USA":fast,
        "Japan":fast
    }
}

var fast = {
    en:"FAST",
    es:"RAPIDO"
}

I can't seem to get it to work though. I would like to refer to the object like this: parent.countryAlerts.USA.LANGUAGE.

Any help is appreciated.

Thanks!

+2  A: 

Yes that is possible, you just have to define fast first:

var fast = {
    en: "FAST",
    es: "RAPIDO"
};
var parent = {
    countryAlerts: {
        "USA" : fast,
        "Japan" : fast
    }
};

var lang = "en";

alert(parent.countryAlerts.USA[lang]); // "FAST"

Note the use of the square bracket notation for accessing an object's members by a variable name.

Edit: In response to the comment:

Ahh, that was silly. Thanks! I have another question now. Let's say I want to store fast in the parent object.

So you mean, like this (pseudo-code)?

var parent = {
    fast : {
        en : "FAST",
        es : "RAPIDO"
    },
    countryAlerts : 
        "USA" : fast    // ** magic here
        "Japan" : fast  // **
    }
};

In short, you can't do it in one statement like that. Your best bet would be to move it to multiple statements.

var parent = {
    fast : {
        en : "FAST",
        es : "RAPIDO"
    }
};
parent.countryAlerts = {
    "USA" : parent.fast,
    "Japan" : parent.fast
};
nickf
Ahh, that was silly. Thanks! I have another question now. Let's say I want to store fast in the parent object. How would I refer to it then?
tau
Thanks! Just what I was looking for. I didn't even think to define countryAlerts outside of parent (I kept getting parent undefined).
tau
+1  A: 

For your follow-up:

var parent = new (function()
{
    var fast = {
      en: "FAST",
      es: "RAPIDO"
    };

    this.countryAlerts = {
        "USA" : fast,
        "Japan" : fast
    };
})();
Matthew Flaschen
Okay, I was trying to avoid defining parent that way, but that works. Thanks!
tau
@tau, yeah. It's impossible to keep `fast` inside `parent` and define `parent` with an object literal.
Matthew Flaschen