How do I add a property to a Javascript Object using a variable as the name?

Posted by Todd R on Stack Overflow See other posts from Stack Overflow or by Todd R
Published on 2009-03-29T18:00:58Z Indexed on 2010/05/17 18:10 UTC
Read the original article Hit count: 140

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about JSON