0

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.

4
  • Search SO for "JavaScript create dynamic key". Commented Jul 5, 2012 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. Commented Jul 5, 2012 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:...}; Commented Jul 5, 2012 at 13:34
  • Cheers! That did the trick. Post it as the answer so I can accept? Commented Jul 5, 2012 at 13:37

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.