-4

Suppose I have an object obj which has some variables in it. What I want to do is to add a new variable which has a name i gave as a parameter. For example:

var obj=
{
  number:8
}

function AddField(field_name,obj)
{
  //some magical code here
}

If I call

AddField('name',obj);

i want to be able to do

obj.name='Apple'

after calling this function.

Any ideas?

zzzzBov
  • 174,988
  • 54
  • 320
  • 367

3 Answers3

5

Use square brackets notation:

obj[field_name] = value;

REF: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId

VisioN
  • 143,310
  • 32
  • 282
  • 281
0

Use the bracket notation:

obj[field_name] = void 0;

This creates a new property with an undefined value.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

If obj is already defined, you can just do obj.field_name = null or obj["field_name"] = null. I wouldn't set any value to undefined even though the language allows for that, simply for a semantic issue: undefined means "this property/variable has not been defined" and null means "this property/variable has no value".

Pablo Mescher
  • 26,057
  • 6
  • 30
  • 33