Search code examples
javascriptobject-literal

How can I pass a JS object literal name value pair to another function


Given a JS literal object like:

var foo = {
    _stuff : {
        a:10,
        b:20,
        c:30,
        state
    }
}

and literal functions

addAB: function() {
    add(foo._stuff[a], foo._stuff[b]);
}

addAC: function() {
    add(foo._stuff[a], foo._stuff[c]);
}

add: function(bar, baz) {
    foo._stuff[bar] += foo._stuff[baz];
    state(foo._stuff[bar]);
}

state: function(value) {
   foo.state[value] = .... something complex ....
}

How can I get the following in one pass ?

add(AB); foo._stuff[a] should be 30, foo.state[foo._stuff[a]] is something new
add(AC); foo._stuff[a] should be 40, foo.state[foo._stuff[a]] is something new

As is add() will try to lookup foo._stuff[10] which clearly wont do what I want.

Yes I know there is redundancy with addAB() and addAC() but that is out of my control.


Solution

  • Pass the index instead of the value, like this:

    addAB: function() {
        add('a', 'b');
    }
    
    addAC: function() {
        add('a', 'c');
    }