0

Assuming I have the following object.

myobj = {
    'item1'{'key1':'value1'},
    'item2'{'key2':'value2'}
}

How can I define a function such that I could call:

var value = getMyObjItem('item2').getValue();

in order to get 'value2'? I would like to avoid defining a 'getItem' (takes item parameter) and 'getItemByValue' (takes two parameters of item and key).

2
  • 2
    First of all, your original javascript is invalid. It should have ":" between the items and the {}. Then you can access the objects directly. e.g. var test = myobj.item2.key2 - jsfiddle.net/USD8f Commented Jan 15, 2014 at 4:34
  • So how would that work if item has more than one key? Commented Jan 15, 2014 at 4:36

1 Answer 1

1

It wasn't clear what you wanted, but I did the best I could with the information I had. The following function operates in the exact manner you asked for, and is probably a good example of giving you what you asked for rather than what you needed. Nonetheless:

myobj = {
    'item1': {'key1':'value1'},
    'item2': {'key2':'value2'}
};

function getMyObjItem(key) {
    return {
        value: myobj[key]["key" + key.replace("item", "")],
        getValue: function() {
            return this.value;
        }
    };
}

var value = getMyObjItem('item2').getValue(); // will return "value2"

Note that this will only work if you maintain the exact property scheme that you demonstrated in the example.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain a little bit exactly how this works? How is value called here? Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.