Search code examples
javascriptprototype-programming

Javascript: Using a pre-existent object values as keys os a new one


I created this object:

var keys = {A: 'a', B: 'b' };

Later I tried create this other object:

var values = {keys.A: 1, keys.B: 2};

However I got this in Firefox console:

SyntaxError: missing : after property id

Even when I tried:

var vals = {keys['A']: 1, keys['B']: 2}

I got the same error.

The only way to get a success is if I type this:

var vals= {};
vals[keys.A] = 1;
vals[keys.B] = 2;

So, my question is if there is a more elegant way (similar to the first try) to create an anonymous object using as keys the values from a pre-existent object.

Thanks,

Rafael Afonso


Solution

  • Yes, the more elegant way is to use ES6 syntax:

    var values = {[keys.A]: 1, [keys.B]: 2};
    

    The thing in brackets can be any expression, so run wild:

    var values = { [createPropName() + "_prop"]: 42 }
    

    This is called "computed (dynamic) property names". See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names.