How can i create object with function parameters?
function hell(par1, par2) {
return { par1 : par2 };
}
hell(ID, 1);
I want return { ID : 1 }
-
1Possible duplicate of Dynamically access object property using variablemelpomene– melpomene2017年01月26日 21:42:23 +00:00Commented Jan 26, 2017 at 21:42
1 Answer 1
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;
}