Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to create the following nested object inside a for loop using JavaScript which then gets pushed to an existing array:

            _spec = {
                _key: {
                    type: _clHndl.getFieldType(_f),
                    editable: true,
                    validation: {
                        required: _clHndl.isRequired(_f),
                        min: 10
                    }
                }
            };

            _arr.push(_spec);

The _key field is dynamic (changes every iteration), I want the identifier of the nested item _key to be the actual value that _key contains in the iteration. Right now it just makes each one '_key' when I use JSON.stringify() to inspect it.

Any help would be appreciated. Thanks for your time.

share|improve this question
    
Search SO for "JavaScript create dynamic key". –  squint Jul 5 '12 at 13:28
    
I know how to make dynamic keys, but in a nested form like this, I'm not sure. I couldn't find an example of this specific context on SO. –  Mr. Smith Jul 5 '12 at 13:32
    
It's no different for nested keys, though yours isn't really nested. It's at the top level of the spec object, so it'll be the same as most other examples given. spec = {}; spec[my_dynamic_key] = {type:...}; –  squint Jul 5 '12 at 13:34
    
Cheers! That did the trick. Post it as the answer so I can accept? –  Mr. Smith Jul 5 '12 at 13:37

1 Answer 1

up vote 1 down vote accepted

Your key isn't really nested (it's at the top level of the outer object), though it wouldn't really be different if it was.

To create a dynamic key, use the square bracket version of the member operator.

spec = {}; 

spec[my_dynamic_key] = {
    type: _clHndl.getFieldType(_f),
    editable: true,
    validation: {
        required: _clHndl.isRequired(_f),
        min: 10
    }
}
share|improve this answer
    
Nice, thank you! :) –  Mr. Smith Jul 5 '12 at 13:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.