1

In JavaScript, is there a shorter way to create object from a variable then below.

var d = 'something';
function map(d){
   var obj = {};
   obj[d] = d;
   return obj;
}

well, the shortest looks like, but it is wrong as key is literal d than its value.

function wrong(d){
   return {d:d}
}

I don't mind the first version, but wonder any succinct way.

thanks.

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
bsr
  • 57,282
  • 86
  • 216
  • 316

1 Answers1

3

I recommend instantiating an anonymous function.

function map(d) {
    return new function () {
        this[d] = d;
    };
}

Using an anonymous function will allow you to keep all of your property declarations in the same place to be more organized. If you need other default keys set you can add them easily:

new function () {
    this[d] = d;
    this.foo = 'bar';
};

Versus with an object literal you'll have declarations in two places:

obj = {
    foo: 'bar'
};
obj[d] = d;

That all said, the original code is fine as-is. It's concise, readable, and maintainable.

function map(d) {
    var obj = {};
    obj[d] = d;
    return obj;
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 5
    Why is this better than what the OP already had? – jfriend00 Feb 24 '14 at 18:11
  • @jfriend00, I don't recall ever saying it was better, but I recommend it because you can keep all initializations in the same place, rather than doing `o = {foo: bar}; o[fizz] = buzz;`. I feel that it keeps the code tidier. – zzzzBov Feb 24 '14 at 18:14
  • @jfriend00, also, the original code **is** actually shorter than what op listed initially, but that's without minification, so it doesn't really make much of a difference – zzzzBov Feb 24 '14 at 18:44
  • I'm not sure why this was downvoted. It is an excellent answer in my opinion. +1 – Paul Feb 24 '14 at 18:49
  • @Paulpro, my initial answer wasn't very good. – zzzzBov Feb 24 '14 at 18:59