Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Create object shorthand

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?

like image 876
dthree Avatar asked Dec 16 '14 22:12

dthree


People also ask

What is object shorthand in JavaScript?

Object property shorthand enables us to simply pass in the name of the key as opposed to repeating the name and the key.

How do you initialize a new object?

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 ( {} ).

What is object literal syntax?

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.


2 Answers

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!

like image 147
Felix Kling Avatar answered Sep 24 '22 21:09

Felix Kling


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.

like image 31
GolezTrol Avatar answered Sep 21 '22 21:09

GolezTrol