2

How can i create object with function parameters?

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

I want return { ID : 1 }

asked Jan 26, 2017 at 21:39
1

1 Answer 1

5

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;
}
answered Jan 26, 2017 at 21:40
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.