Sig
Sig

Reputation: 5916

Setting ajax data from data attribute

Is there a better way to set data from a data attribute then

$.ajax({
  url: $(this).data('update-url'),
  type: "PUT",
  data: { 
    batch_phase: { 
      "#{$(this).data('attribute')}": new Date().toUTCString() 
    }
  }
});

I don't really like "#{$(this).data('attribute')}".

Upvotes: 1

Views: 40

Answers (2)

Igor
Igor

Reputation: 15893

You can construct data [sub]object with the key defined using bracket notation:

var data = {};
data[$(this).data('attribute')] = new Date().toUTCString();
$.ajax({
  url: $(this).data('update-url'),
  type: "PUT",
  data: { batch_phase: data }
});

Upvotes: 2

Taplar
Taplar

Reputation: 24965

You can use [] around the key to make it evaluate a variable to be an object key.

var aVariable = "me";
var object = {
  [aVariable]: 'weee'
};
console.log(object);

Upvotes: 1

Related Questions