1

Possible Duplicate:
How to create object property from variable value in javascript?

OK - this is a tough on for me. I am looping through all of my classes="data" using jQuery. I then want to assign properties to my feature using each specific "dataName" and "dataValue". However, once complete, I only have a a propery of "dataName=(the last value looped)". How can I assign my dataName variable to create a new property each time - instead of thinking I only want to create a property named "dataValue"

function pushAttributesintoFeature(feature) {  
  $(".data").each( function(){
    var dataName = $(this).attr("name")
    var dataValue = $(this).val()   
    feature.dataName = dataValue
  })
}

Example:

<input class="data" name="radius" value="15">
<input class="data" name="height" value="5">

Once I execute the script, I am left with: feature.dataName = "5" But I want: feature.radius="15" AND feature.height = "5"

Community
  • 1
  • 1
Kyle
  • 61
  • 1
  • 1
  • 7

3 Answers3

2

You can use the square bracket syntax to access a property with a variable:

feature[dataName] = dataValue;

This will set a property whose identifier is the value of dataName, rather than the literal string "dataName".

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

You can write your code like this:

feature[$(this).attr("name")] = $(this).val()
gabitzish
  • 9,535
  • 7
  • 44
  • 65
0

Use this sintax for setting the values:

function pushAttributesintoFeature(feature) {  
  $(".data").each( function(){
    var dataName = $(this).attr("name")
    var dataValue = $(this).val()   
    feature[dataName] = dataValue;
  })
}
VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • "Syntax like this... is equivalent to this"... no it's not, that's the whole point! Did you miss the quotes around `dataName` in the first example? That would make them equivalent. – James Allardice Dec 20 '12 at 13:59
  • @James Allardice You've misunderstand my answer. But I've edited it to avoid future misuderstandings. – VMAtm Dec 20 '12 at 18:04