1

I have this simple object.

var myobj = {
   id: value
}

But instead of having a property named "id" I want the property identifier to be the value of:

$(this).attr('id');

I cannot preset this as I do not know the ID of the element. I want to be able to get my property value by

<id-of-element>.id

I understand I cannot do like this:

var myobj = {
   $(this).attr('id'): value
}

but how can I solve it? :)

Andreas Norman
  • 990
  • 1
  • 8
  • 18
  • possible duplicate of [create object using variables for property name](http://stackoverflow.com/questions/3153969/create-object-using-variables-for-property-name) – Oriol Aug 15 '14 at 19:47

2 Answers2

5

You can't assign a dynamic property name like that, but you can use the [] notation:

var myobj = {};
myobj[$(this).attr('id')] = value;
MrCode
  • 61,589
  • 10
  • 82
  • 110
0

ES6 introduces computed property names, which allow you to do

var myobj = {
   [$(this).attr('id')]: value
}

Note browser support is currently negligible.

Oriol
  • 249,902
  • 55
  • 405
  • 483