Dan Kanze
Dan Kanze

Reputation: 18595

assign object as key value in javascript

I am tyring to do something like this:

this.slides = {$('#Page_1') : null,
               $('#Page_2') : null,
               $('#Page_3') : null};

Why am I doing this, or what advantage do I gain?
I dont want to use jquery selectors throughout class.


A Solution:

this.slides = [{"key": $('#Page_1'), "value": null},
               {"key": $('#Page_2'), "value": null},
               {"key": $('#Page_3'), "value": null}];

Limitation:

The problem with this approach is that you have to iterate through the whole object each time you want to approach this. You should use the id as identifier, this is much more efficient. – Christoph

Upvotes: 0

Views: 124

Answers (4)

Christoph
Christoph

Reputation: 51181

You cannot use objects as keys, only plain literals. I'd suggest a structure like this:

this.slides = { 'Page_1' : $('#Page_1'),
                'Page_2' : $('#Page_2')
                'Page_3' : $('#Page_3')};

This way you can use the id of the elements to easily access the according jQuery-Object. (You can omit the quotes for the keys.)

slides.Page_1
// or
slides['Page_1']

now gives you the according jQuery Object.

Upvotes: 1

j_mcnally
j_mcnally

Reputation: 6958

No, keys must be literals. you could use a property of your object.

Upvotes: 3

Ian
Ian

Reputation: 50905

Why don't you try a structure like this:

this.slides = [{"key": $('#Page_1'), "value": null},
               etc.];

Or does that break your need for using an object?

Of course, when iterating it, you'd have to use logic like:

for (var i = 0; i < this.slides.length; i++) {
    var key = this.slides[i].key;
    var value = this.slides[i].value;
}

Upvotes: 1

dweeves
dweeves

Reputation: 5605

If your processing is based on the this.slides content, why not use the id as key ? since they are also meant to be "unique" otherwise you would break the DOM. So i would suggest something like

this.slides = {'#Page_1':null,'#Page_2':null,'#Page_3':null};

And a very light modification of your processing of this.slides

Upvotes: 2

Related Questions