-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?

3
  • 1
    You want to add a field without value ? Why ? Commented May 14, 2013 at 13:26
  • You could always just call obj.name = 'Apple', if you'd tried it, you'd know it works Commented May 14, 2013 at 13:26
  • initialize ''name'' in the constructor of AddField Commented May 14, 2013 at 13:28

3 Answers 3

5

Use square brackets notation:

obj[field_name] = value;

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

Sign up to request clarification or add additional context in comments.

4 Comments

OP doesn't seem to want to add a value, just a field.
@dystroy Then value = undefined.
Maybe. In fact I don't get what's the real question.
So simple, yet perfect for my need, thank you. I will accept the answer as soon as i can.
0

Use the bracket notation:

obj[field_name] = void 0;

This creates a new property with an undefined value.

Comments

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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.