benhowdle89
benhowdle89

Reputation: 37464

Nested object with square bracket notation in JavaScript

I'm trying to achieve the following:

this.inputs[options.el.find('form').attr('class')] = {};

this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;

However, I'm unable to do the above without a syntax error!

Any ideas how I could achieve this Object structure?

Upvotes: 1

Views: 3719

Answers (2)

AlexStack
AlexStack

Reputation: 17381

The index to an object should always be a string:

var obj = {
  a: 2;
}

obj.a = 3; //a is 3 now
obj['a'] = 4;//a is 4 now

You said options.elements[x].selector is input[name="username"] so I guess in this line:

this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;

What you are really trying to do is:

this.inputs[options.el.find('form').attr('class')]['username'] = false;

So you can do like this:

var sel = options.elements[x].selector;
console.log( 'sel is ' + sel );
this.inputs[options.el.find('form').attr('class')][sel] = false;

Make sure that sel is a string. You may want to try

var sel = options.elements[x].selector.value;

The .value bit retrieves the text from inside an input element.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187034

That syntax looks legal, but these long one liners aren't doing anyone any favors. Break it apart a bit so you can find where it's failing.

var className = options.el.find('form').attr('class');
var selector = options.elements[x].selector;

this.inputs[className] = {};
this.inputs[className][selector] = false;

Upvotes: 2

Related Questions