cjm2671
cjm2671

Reputation: 19456

Associative style arrays in Javascript?

I'm trying to assign an object in the style of an associate array in JS but it's failing, saying 'task.id' is undefined. Why is this?

var response = Object();
$('.task-list').each(function() {
  response[this.id][$('#' + this.id).sortable('toArray')];
});

Upvotes: 1

Views: 145

Answers (2)

Tom Hubbard
Tom Hubbard

Reputation: 16129

You are referencing the object as a two dimensional array.

You should do it more like this:

var response = {};
$(".task-list").each(function () {
    response[this.id] = $(this).sortable('toArray');
}

Also, when you say the error is "task.id is undefined", do you mean "this.id is undefined"? If you are selecting elements based on class, they may not have an explicit id.

<span class="task-list">myTask</span>

You may want to include an id:

<span class="task-list" id="myTask">myTask</span>

Upvotes: 5

Richard Dalton
Richard Dalton

Reputation: 35793

You are trying to access a property that you haven't created yet. Although it's not actually clear what you are trying to do from your example. I'm assuming you want to set the value of response[this.id] to $('#' + this.id).sortable('toArray')?

Try this instead:

var response = {};
$('.task-list').each(function() {
    response[this.id] = $(this).sortable('toArray');
});

Also changed it to use $(this) instead of $('#' + this.id) as it's cleaner imo.

Upvotes: 0

Related Questions