2

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";
Cera
  • 1,879
  • 2
  • 20
  • 29
  • 2
    Why are you trying to achieve that? What is it you're trying to do? – Jared Farrish Dec 07 '11 at 02:01
  • 1
    No. Same as this question: http://stackoverflow.com/questions/7047209/is-there-any-way-to-use-a-dynamic-key-with-node-mongodb-native/7047266#7047266 – gilly3 Dec 07 '11 at 02:03
  • I believe this `var str = 'foo'; var obj = { [str]: 'bar' };` will be valid in ES6. – Šime Vidas Dec 07 '11 at 02:08
  • Jarred - I was hoping to have a nice syntax for defining CouchDB design documents whose inline appearance maps directly to the stringified JSON form. Looks like a helper method is the best way to achieve this. – Cera Dec 07 '11 at 04:41

2 Answers2

4

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"}
RightSaidFred
  • 11,209
  • 35
  • 35
2

No. Object literals cannot use the values of variables as keys. The fact that you can quote the keys may make it seem like real values go there, but they do not.

James Clark
  • 1,765
  • 13
  • 17