Take the below object:
var value = 'bar';
var obj = { foo: value }
// -> Object { foo="bar" }
Supposing the key was also a variable, one could go:
var key = 'foo', value = 'bar';
var obj = {}
obj[key] = value;
// -> Object { foo="bar" }
Now, I want to do this in one line (shorthand). So I tried:
var obj = {}[key] = value; // or,
var obj = ({})[key] = value; // or,
var obj = new Object()[key] = value;
// -> "bar"
This oddly produces a String instead of an Object.
Is there any way to do this shorthand?
Object property shorthand enables us to simply pass in the name of the key as opposed to repeating the name and the key.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
ECMAScript 6 will allow you to do
var obj = {
[key]: value
};
Browser support is not great yet, but transpilers such as 6to5 allow you to use this notation today!
You can, or almost can. If you put the creation of the object, and its assignment to obj
in parentheses, you can set a property of the result of that expression:
var obj, key='foo', value = 'bar';
(obj = {})[key] = value;
alert(obj); // [object Object]
alert(obj.foo); // bar
The var
keyword cannot be included in that expression within parentheses, so either you will have to declare obj before (like I did), or not declare it at all and accept that it will be in global scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With