JS - creating a shorthand object
Take the object below:
var value = 'bar';
var obj = { foo: value }
// -> Object { foo="bar" }
Assuming the key is also a variable, one can go:
var key = 'foo', value = 'bar';
var obj = {}
obj[key] = value;
// -> Object { foo="bar" }
Now I want to do it 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 weirdly creates a string instead of an object.
Is there a way to do this reduction?
source to share
ECMAScript 6 will let you do
var obj = {
[key]: value
};
Browser support is still small, but transpilers such as 6to5 allow you to use this notation today!
source to share
You can, or you can almost. If you put the creation of an object and its assignment in obj
parentheses, you can set the result property of that expression:
var obj, key='foo', value = 'bar';
(obj = {})[key] = value;
alert(obj); // [object Object]
alert(obj.foo); // bar
The keyword var
cannot be included in this expression in parentheses, so either you have to declare obj earlier (like I did), or not declare it at all, but agree that it will be in the global scope.
source to share
ECMAScript 5 (current version) lacks shorthand, but you can make the method
function createObject(key, value /*, key, value, ... */ ) {
var object = {};
for (var i = 0; i < arguments.length; i = i + 2) {
object[arguments[i]] = arguments[i+1];
}
return object;
}
Then you can call it like this
var obj = createObject(key, value, 'anotherKey', 'anotherVal');
source to share
Something like this is included in ECMAScript 6 :
As of ECMAScript 6, there is a shorter notation available to achieve the same:
var a = "foo", b = 42, c = {}; // Shorthand property names (ES6) var o = { a, b, c };
So you can create your object with the following code
var foo = 'bar';
var obj = {foo};
source to share