In JavaScript, I\'ve created an object like so:
var data = {
\'PropertyA\': 1,
\'PropertyB\': 2,
\'PropertyC\': 3
};
Is it poss
I was looking for a solution where I can use dynamic key-names inside the object declaration (without using ES6 features like ...
or [key]: value
)
Here's what I came up with:
var obj = (obj = {}, obj[field] = 123, obj)
It looks a little bit complex at first, but it's really simple. We use the Comma Operator to run three commands in a row:
obj = {}
: creates a new object and assigns it to the variable obj
obj[field] = 123
: adds a computed property name to obj
obj
: use the obj
variable as the result of the parentheses/comma listThis syntax can be used inside a function parameter without the requirement to explictely declare the obj
variable:
// The test function to see the result.
function showObject(obj) {
console.log(obj);
}
// My dynamic field name.
var field = "myDynamicField";
// Call the function with our dynamic object.
showObject( (obj = {}, obj[field] = 123, obj) );
/*
Output:
{
"myDynamicField": true
}
*/
The above code does not work in strict mode
because the variable "obj" is not declared.
// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );
// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );
This solution works in all modern browsers (but not in IE, if I need to mention that)
JSON.parse()
:// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );
Note that you can also use spaces and other special characters inside computed property names (and also in JSON.parse).
var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }
Those fields cannot be accessed using a dot (obj.my dynamic field :)
is obviously syntactically invalid), but only via the bracket-notation, i.e., obj['my dynamic field :)']
returns 123