views:

1088

answers:

2

I'm pulling items out of the DOM with JQuery and want to set a property on an object using the id of the DOM element. For example:

obj = {};
jQuery(itemsFromDom).each(function() {
  element = jQuery(this);
  name = element.attr("id");
  value = element.attr("value");

  //Here's the problem
  obj.name = value;
});

If "itemsFromDom" includes an element with an id of "myId", I want "obj" to have a property named "myId". The above gives me "name".

How, in javascript, do I name a property of an object using a variable?

+21  A: 

You can use this equivalent syntax:

obj[name] = value;
CMS
Thanks! Exactly what I was looking for.
Todd R
A: 

You cannot have a variable property. You can loop through the object as an array...

for (property in object) {
object[property] = value;
}

unfortunately there is no other way.

Alex V