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.

4
  • Yup, use the first way. The second way, the key will be d, not the value of d. Commented Feb 24, 2014 at 18:05
  • Out of curiousity, if the name of the key is always the value why do you need to store it as both? Commented Feb 24, 2014 at 18:09
  • what about using obj.d = d; ? Commented Feb 24, 2014 at 18:13
  • 2
    @RajeshCP - because that doesn't work. Commented Feb 24, 2014 at 18:15

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why is this better than what the OP already had?
@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.
@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
I'm not sure why this was downvoted. It is an excellent answer in my opinion. +1
@Paulpro, my initial answer wasn't very good.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.