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?

+3


source to share


5 answers


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!

+5


source


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
      

Run codeHide result


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.

+5


source


Depending on what you call a one-liner, with some golf code, you can do

var obj = (function(o) {o[key]=value; return o})({});

      

he thinks the shortest you get it?

+3


source


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');

      

0


source


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};

      

0


source







All Articles