giorgi chaduneli
giorgi chaduneli

Reputation: 23

Create object with function parameters

How can i create object with function parameters?

function hell(par1, par2) {
 return { par1 : par2 };
}
hell(ID, 1);

I want return { ID : 1 }

Upvotes: 2

Views: 2341

Answers (1)

Pointy
Pointy

Reputation: 413702

In modern JavaScript:

function hell(par1, par2) {
 return { [par1] : par2 };
}
hell("ID", 1);

The brackets ([ ]) around the property name means that the name should be the value of the enclosed expression.

Note also that when you call the function, the value of the first argument should be a string. I changed your code to use "ID" instead of just ID; if you have a variable floating around named ID, of course, that'd be fine, so long as it can evaluate to a string.

This is a fairly recent addition to the language. If your code should run in old browsers, you'd have to do something like this:

function hell(par1, par2) {
 var obj = {};
 obj[par1] = par2;
 return obj;
}

Upvotes: 5

Related Questions