1

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')}".

2 Answers 2

2

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 }
});
Sign up to request clarification or add additional context in comments.

3 Comments

You're right - I misread your code. This is why it's always best to explain the problem and why your solution helps ;)
@RoryMcCrossan I thought the onus of explaining the problem was on a topic starter :)
That depends on whether they fully understand it or not
1

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);

Comments

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.