0

I want to know if its possible (and correct) to construct a named index array that is associated with other arrays.

E.g.,

var signOptionSet = [];
signOptionSet['basic'] = ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'];
signOptionSet['advanced'] = ['Area', 'Perimeter', 'Lighting'];

How would I access something like 'Sign Height' in signOptionSet['basic']?

2 Answers 2

3

I want to know if its possible...

Yes, although the way you're using it, you wouldn't want an array, you'd just want an object ({}) (see below).

...(and correct)...

Some would argue that using an array and then adding non-index properties to it is not correct. There's nothing technically wrong with it, provided you understand that some things (such as JSON.stringify) won't see those non-index properties.

How would I access something like 'Sign Height' in signOptionSet['basic']?

It's the second entry, so index 1, of the array you've assigned to signOptionSet['basic'], so:

var x = signOptionSet['basic'][1];

or

var x = signOptionSet.basic[1];

Using an object, and using property name literals as there's no need for strings here, would look like this:

var signOptionSet = {
    basic: ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    advanced: ['Area', 'Perimeter', 'Lighting']
};

You can use strings, though, if you prefer:

var signOptionSet = {
    "basic": ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    "advanced": ['Area', 'Perimeter', 'Lighting']
};

Both single and double quotes are valid in JavaScript (single quotes wouldn't be in JSON, but this isn't JSON, it's JavaScript):

var signOptionSet = {
    'basic': ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    'advanced': ['Area', 'Perimeter', 'Lighting']
};
Sign up to request clarification or add additional context in comments.

Comments

0

You access the value 'Sign Height' like

alert(signOptionSet['basic'][1]) // 'Sign Height'

Fiddle

2 Comments

This worked, but the answer by Crowder was more complete to my query.
@Matthew6 His answer is exactly what you should seek to understand to go about your trouble. :)

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.