views:

85

answers:

4

I need to store values that would look like this:

"somekey": "value1", "value2"

So I want to create a function that will take in "somekey", and it will return "value1", "value2".

It doesn't have to be a function, it could easily be a collection that I initialize in my javascript file and then reference like:

var v1 = blah("somekey").value1;
var v2 = blah("somekey").value2;

I know this is possible, I just don't know enough to get a handle on this yet!

+4  A: 
function getTwoValues()
{
    return ['value1', 'value2'];
}

var values = getTwoValues();
alert("Value 1 is " + values[0]);
alert("Value 2 is " + values[1]);
Trevor
+3  A: 

you could return an object from the function

function getTwoValues()
{
    return {
        value1 : 'value1', 
        value2 : 'value2'
    };
}

which would allow you to do

var v1 = getTwoValues().value1; // 'value1'
var v2 = getTwoValues().value2; // 'value2'
Russ Cam
creating a function like Russ Cam says here also has the added benefit of creating a closure, allowing you to do some private processing within the function before returning the object containing the values.
richleland
A: 

tvor shows how to do it with an Array. If you're interested in creating a "collection" like you outlined with "blah" you could just create an object.

var blah = {};
blah["somekey"] = {value1:"foo", value2:"bar"};
alert(blah["somekey"].value1);
alert(blah["somekey"].value2);

To keep it tidy I suppose you could also include a "Tuple" object:

function Tuple(value1, value2) {
  this.value1 = value1;
  this.value2 = value2;
}

blah["somekey"] = new Tuple("foo", "bar");
Matt Baker
+4  A: 
var map = {
    somekey: {value1: "value1", value2: "value2" },
    somekey2: {value1: "value21", value2: "value22" },
    somekey3: {value1: "value31", value2: "value32" }
};

alert(map["somekey"].value1);
alert(map["somekey3"].value2);

Also, since "associative arrays" in javascript are really objects, you can just use object notation if you are statically getting a specific value (as Russ mentioned in the comments):

map.somekey.value1

Though this isn't very useful for dynamically getting values from the associative array.

joshperry
@josh - missing a `,` after the second property of map. Could also do `map.somekey.value1`, etc. to get the values
Russ Cam