javascriptobject-literal

Is it possible to use a variable's value as an object key inside an object literal expression?


I want to do something along these lines:

var firstName = "alan";
var secondName = "antonella";
var statusOfPeople = {
    firstName: "excellent",
    secondName: "superb"
};
console.log(JSON.stringify(statusOfPeople));

And get this output:

{ "alan": "excellent", "antonella": "superb" }

Is this possible? Without doing this?

var statusOfPeople = {};
statusOfPeople[firstName] = "excellent";
statusOfPeople[secondName] = "superb";

Solution

  • No, not directly in the object literal declaration.

    It would be impossible to tell if you intended the variable value, or the identifier itself as the property name.


    You could create a helper function that takes arrays of key/value pairs if you wanted:

    function makeObject() {
        var obj = {};
        for( var i = 0; i < arguments.length; ++i ) {
            obj[ arguments[i][0] ] = arguments[i][1];
        }
        return obj;
    }
    

    And use it like:

    var firstName = "alan";
    var secondName = "antonella"; 
    
    var statusOfPeople = makeObject(
        [firstName, "excellent"],
        [secondName, "superb"]
    );
    
    console.log(JSON.stringify(statusOfPeople)); 
    
    // {"alan":"excellent","antonella":"superb"}
    

    You could even reduce the syntax a bit if you did it like this:

    function makeObject() {
        var obj = {};
        for( var i = 0; i < arguments.length; i+=2 ) {
            obj[ arguments[i] ] = arguments[i+1];
        }
        return obj;
    }
    

    And used it like this:

    var firstName = "alan";
    var secondName = "antonella"; 
    
    var statusOfPeople = makeObject(
        firstName, "excellent",
        secondName, "superb"
    );
    
    console.log(JSON.stringify(statusOfPeople)); 
    
    // {"alan":"excellent","antonella":"superb"}