Alexander Kleinhans
Alexander Kleinhans

Reputation: 6258

JS return object by array index

I'm trying to convert an array to an object (keyed by the first element).

foo = [1,2]

function convert_foo(foo) {
    return { foo[0]: foo[1] };
}

The following is not valid Javascript: Uncaught SyntaxError: Unexpected token [.

I've also tried:

function convert_foo(foo) {
    return ({ foo[0]: foo[1] });
}

EDIT:

It's possible this way, but I was wondering if there was a way to return it in one line.

function convert_foo(foo) {
    var obj = {}
    obj[foo[0]] = foo[1];
    return obj;
}

Upvotes: 2

Views: 5729

Answers (2)

Shidersz
Shidersz

Reputation: 17190

With the upcoming Object.fromEntries(), that is already supported on some browsers, you can also do something like this:

function convert_foo(foo)
{
    return Object.fromEntries([foo]);
}

console.log(convert_foo([1, 2]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97282

For dynamic keys (aka computed property names in ECMAScript 2015), you have to put the key in square brackets:

function convert_foo(foo) {
    return { [foo[0]]: foo[1] };
}

console.log(convert_foo([1, 2]));

Upvotes: 4

Related Questions